Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Reciprocal

 

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)

 

 

 

 

 

The general algorithm way

 

*        View 'The general algorithm way' of 'Reciprocal' in plain text

 

 

#include <algorithm>

#include <numeric>

 

//From http://www.richelbilderbeek.nl/CppReciprocal.htm

template <class Container>

void Reciprocal (Container& c)

{

std::transform(c.begin(),c.end(),c.begin(),

std::bind1st(std::divides<Container::value_type>(),1.0));

}

 

 

 

 

The algorithm way on a std::vector < double >

 

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

 

 

#include <vector>

#include <algorithm>

#include <numeric>

 

//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));

}

 

 

 

 

 

 

The for -loop way on a std::vector < double >

 

Prefer algorithms over loops [0] [1] .

 

*        View 'The for-loop way on a std::vector<double>' of 'Reciprocal' in plain text

 

 

#include <vector>

 

//From http://www.richelbilderbeek.nl/CppReciprocal.htm

void Reciprocal (std::vector<double>& v)

{

const int sz = v.size();

for (int i=0; i!=sz; ++i)

{

v[i]=1.0/v[i];

}

}

 

 

 

 

 

 

References

[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.