(C++) Reciprocal
January 7, 2018 · View on GitHub
(C++) Reciprocal
Reciprocal is a 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
#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.
#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 [1,2].
#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
- Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
- 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.'