Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Triple

 

Container code snippet to triple all values in a container.

 

There are multiple ways to perform Triple:

 

 

 

 

 

C++98STL 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));
}

 

 

 

 

 

C++98Boost 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;
  }
}

 

 

 

 

 

C++98Boost 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);
}

 

 

 

 

 

C++98STL 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));
}

 

 

 

 

 

C++11STL 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; } );
}

 

 

 

 

 

C++98 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;
  }
}

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms over loops'
  2. 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.

 

Valid XHTML 1.0 Strict