Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #14: Make square

 

Replace the for-loop. You will need:

 

#include <vector>

void MakeSquare(std::vector<int>& v)
{
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    v[i]*=v[i];
  }
}

 

 

 

 

 

Answer

 

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

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

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

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict