Container code snippet to triple all values in a container.
There are multiple ways to perform Triple:
- The general algorithm way using std::bind2nd
- The general algorithm way using BOOST_FOREACH
- The general algorithm way using boost::lambda
- The C++98 algorithm way on a std::vector<int>
- Using a C++11 lambda expressions on a std::vector<int>
- The for-loop way on a std::vector<int>
The general algorithm way using std::bind2nd
#include <algorithm> #include <numeric> #include <functional> //From http://www.richelbilderbeek.nl/CppTriple.htm template <class Container> void Triple(Container& c) { std::transform(c.begin(),c.end(),c.begin(), std::bind2nd(std::multiplies<typename Container::value_type>(),3)); }
The general algorithm way using BOOST_FOREACH
#include <boost/foreach.hpp> //From http://www.richelbilderbeek.nl/CppTriple.htm template <class Container> void Triple(Container& c) { BOOST_FOREACH(typename Container::value_type& i, c) { i*=3; } }
The general algorithm way using boost::lambda
#include <algorithm> #include <boost/lambda/lambda.hpp> template <class Container> void Triple(Container& c) { std::for_each(c.begin(),c.end(), boost::lambda::_1 *=3); }
The C++98 algorithm way on a std::vector<int>
This version is given as the answer of Exercise #9: No for-loops.
#include <vector> #include <algorithm #include <numeric> //From http://www.richelbilderbeek.nl/CppTriple.htm void Triple(std::vector<int>& v) { std::transform(v.begin(),v.end(),v.begin(), std::bind2nd(std::multiplies<int>(),3)); }
Using a C++11 lambda expressions on a std::vector<int>
#include <algorithm> #include <vector> //From http://www.richelbilderbeek.nl/CppTriple.htm void TripleCpp0x(std::vector<int>& v) { std::for_each(v.begin(),v.end(), [](int& i) { i*=3; } ); }
The for-loop way on a std::vector<int>
Prefer algorithms over loops [1][2]
#include <vector> //From http://www.richelbilderbeek.nl/CppTriple.htm void Triple(std::vector<int>& v) { const int sz = v.size(); for (int i=0; i!=sz; ++i) { v[i]*=3; } }
- 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'