Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #2: Multiply

 

Replace the for-loop. You will need

 

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

 

 

 

 

 

Answer using STL only

 

#include <vector>
#include <algorithm>
#include <numeric>
 
void Multiply(std::vector<int>& v, const int x)
{
  std::transform(v.begin(),v.end(),v.begin(),
    std::bind2nd(std::multiplies<int>(),x));
}

 

 

 

 

 

Answer using Boost

 

#include <vector>
#include <algorithm>
#include <numeric>
#include <boost/bind.hpp>
 
void Multiply(std::vector<int>& v, const int x)
{
  std::transform(v.begin(),v.end(),v.begin(),
    boost::bind(std::multiplies<int>(),_1,x));
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict