Skip to content

Latest commit

 

History

History
56 lines (40 loc) · 4.44 KB

CppAdd.md

File metadata and controls

56 lines (40 loc) · 4.44 KB

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. C++11STL The C++11 algorithm way on a std::vector<int>
  2. C++98STL The C++98 algorithm way on a std::vector<int>
  3. C++98 The for-loop 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; }

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.

C++98 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.'