Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #17: Halve

 

Replace the for-loop. You will need:

 

#include <vector>

void Halve (std::vector<double>& v)
{
  const int sz = static_cast<int>(v.size());
  for (int i=0; i!=sz; ++i)
  {
    v[i]/=2.0;
  }
}

 

 

 

 

 

Answer

 

#include <algorithm>
#include <numeric>
#include <vector>

//From http://www.richelbilderbeek.nl/CppHalve.htm
void Halve (std::vector<double>& v)
{
  std::transform(v.begin(),v.end(),v.begin(),
    std::bind2nd(std::divides<double>(),2.0));
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict