Add is a math code snippet to add a certain same value to each element in a std::vector.
There are multiple ways to perform Add:
- The C++11 algorithm way on a std::vector<int>
- The C++98 algorithm way on a std::vector<int>
- The for-loop way on a std::vector<int>
The C++11 algorithm way on a std::vector<int>
Prefer algorithms over loops [1][2]
#include <algorithm> #include <vector> //From http://www.richelbilderbeek.nl/CppAdd.htm const std::vector<int> AddCpp0x(const std::vector<int>& v, const int x) { std::vector<int> w(v); std::for_each(w.begin(),w.end(),[x](int&i) { i+=x; } ); return w; }
The C++98 algorithm way on a std::vector<int>
Prefer algorithms over loops [1][2]
#include <algorithm> #include <functional> #include <numeric> #include <vector> //From http://www.richelbilderbeek.nl/CppAdd.htm const std::vector<int> Add(const std::vector<int>& v, const int x) { std::vector<int> v_new; std::transform(v.begin(),v.end(),std::back_inserter(v_new), std::bind2nd(std::plus<int>(),x)); return v_new; }
This is the answer of Exercise #9: No for-loops.
The for-loop way on a std::vector<int>
Prefer algorithms over loops [1][2]
#include <vector> const std::vector<int> Add(const std::vector<int>& v, const int x) { std::vector<int> v_new(v); //Copy original vector const int sz = v.size(); for (int i=0; i!=sz; ++i) { v_new[i]+=x; } 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.'