Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Answer of exercise #9: No for-loops #13

 

This is the answer of Exercise #9: No for-loops.

 

 

 

 

 

Question #13: MakeAbs

 

Replace the for-loop. You will need:

 

#include <cmath>
#include <vector>
 
void MakeAbs(std::vector<int>& v)
{
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    v[i] = std::abs(v[i]);
  }
}

 

 

 

 

 

Answer

 

#include <algorithm>
#include <cmath>
#include <functional>
#include <vector>

template <class T> struct Abs : public std::unary_function<T,T>
{
  const T operator()(const T& x) const { return std::abs(x); }
};

void MakeAbs(std::vector<int>& v)
{
  std::transform(v.begin(),v.end(),v.begin(),Abs<int>());
}

 

Note: I did not find any way to refrain from writing a functor (for example, by using std::ptr_fun) as shown in the lines below...

 

std::transform(v.begin(),v.end(),v.begin(),std::abs); //Does not work
std::transform(v.begin(),v.end(),v.begin(),&std::abs); //Does not work
std::transform(v.begin(),v.end(),v.begin(),std::ptr_fun(&std::abs)); //Does not work
std::transform(v.begin(),v.end(),v.begin(),std::ptr_fun(std::abs)); //Does not work

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict