Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
Container code snippet to replace all values in a container by their reciprocal (that is: 1/x) (view the wikipedia page on reciprocal).
There are multiple ways to perform Reciprocal:
* The general algorithm way (best)
* The algorithm way on a std::vector<double> (intermediate)
* The for-loop way on a std::vector<double> (worst)
* View 'The general algorithm way' of 'Reciprocal' in plain text
//From http://www.richelbilderbeek.nl/CppReciprocal.htm
void Reciprocal (Container& c)
{
std::transform(c.begin(),c.end(),c.begin(),
std::bind1st(std::divides<Container::value_type>(),1.0));
}
This way is used as an answer in Exercise #9: No for-loops.
* View 'The algorithm way on a std::vector<double>' of 'Reciprocal' in plain text
//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));
}
Prefer algorithms over loops [0] [1] .
* View 'The for-loop way on a std::vector<double>' of 'Reciprocal' in plain text
//From http://www.richelbilderbeek.nl/CppReciprocal.htm
void Reciprocal (std::vector<double>& v)
{
{
v[i]=1.0/v[i];
}
}
[0] Bjarne Stroustrup . The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
[1] Herb Sutter and Andrei Alexandrescu . C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops.'
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.