Math code snippet to add two to all elements in a container.
There are multiple ways to implement AddTwo:
- Using a C++98 algorithm
- Using a C++11 lambda expressions
- Using a for-loop
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; }
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; }
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; }
- [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.'