Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #16: Reciprocal

 

Replace the for-loop. You will need:

 

#include <vector>

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

 

 

 

 

 

Answer

 

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

//From http://www.richelbilderbeek.nl/CppReciprocal.htm
void Reciprocal (std::vector<double>& v)
{
  std::transform(v.begin(),v.end(),v.begin(),
    std::bind1st(std::divides<double>(),1.0));
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict