Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) AddTwo

 

Math code snippet to add two to all elements in a container.

 

There are multiple ways to implement AddTwo:

  1. C++98STL Using a C++98 algorithm
  2. C++11STL Using a C++11 lambda expressions
  3. C++98 Using a for-loop

 

 

 

 

 

 

C++98STL AddTwo using an algorithm

 

This is the anwer of exercise #9: No for-loops #1.

 

#include <vector>
#include <algorithm>
#include <numeric>

const std::vector<int> AddTwo(const std::vector<int>& v)
{
  std::vector<int> v_new;
  std::transform(v.begin(),v.end(),std::back_inserter(v_new),
    std::bind2nd(std::plus<int>(),2));
  return v_new;
}

 

 

 

 

 

C++11STL Using a C++11 lambda expressions

 

#include <algorithm>
#include <vector>

//From http://www.richelbilderbeek.nl/CppAddTwo.htm
const std::vector<int> AddTwo(const std::vector<int>& v)
{
  std::vector<int> w(v);
  std::for_each(w.begin(),w.end(), [](int& i) { i+=2; } );
  return w;
}

 

 

 

 

 

C++98 AddTwo using a for-loop

 

Prefer algorithms over loops [1][2].

 

#include <vector>
 
const std::vector<int> AddTwo(const std::vector<int>& v)
{
  std::vector<int> v_new(v); //Copy original vector
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    v_new[i]+=2;
  }
  return v_new;
}

 

 

 

 

 

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