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:

1. The C++11 algorithm way on a std::vector<int>
2. The C++98 algorithm way on a std::vector<int>
3. The for-loop way on a std::vector<int>

## The C++11algorithm way on a std::vector<int>

Prefer algorithms over loops [1][2]

 ``` #include #include //From http://www.richelbilderbeek.nl/CppAdd.htm const std::vector AddCpp0x(const std::vector& v, const int x) {   std::vector w(v);   std::for_each(w.begin(),w.end(),[x](int&i) { i+=x; } );   return w; } ```

## The C++98algorithm way on a std::vector<int>

Prefer algorithms over loops [1][2]

 ``` #include #include #include #include //From http://www.richelbilderbeek.nl/CppAdd.htm const std::vector Add(const std::vector& v, const int x) {   std::vector v_new;   std::transform(v.begin(),v.end(),std::back_inserter(v_new),     std::bind2nd(std::plus(),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 const std::vector Add(const std::vector& v, const int x) {   std::vector 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; } ```

## 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.'