Skip to content

Latest commit

 

History

History
148 lines (87 loc) · 4.22 KB

File metadata and controls

148 lines (87 loc) · 4.22 KB

 

 

 

 

 

 

GetSum is a container code snippet to sum all values in a one-dimensional container. To sum all values in a two-dimensional matrix, go to the GetSum (on matrix) page.

 

There are multiple ways to perform GetSum:

 

  • The general algorithm way (best)
  • The algorithm way on a std::vector<int> (intermediate)
  • The for-loop way on a std::vector<int> (worst)

 

 

 

 

 

The general algorithm way

 

 


#include <algorithm> #include <numeric> #include <vector> //From http://www.richelbilderbeek.nl/CppGetSum.htm template <class T> const T::value_type GetSum(const T& v) {   return std::accumulate(v.begin(), v.end(), static_cast<T::value_type>(0.0)); }

 

 

 

 

 

The algorithm way on a std::vector<int>

 

This version is given as the answer of Exercise #9: No for-loops.

 

 


#include <algorithm> #include <numeric> #include <vector> //From http://www.richelbilderbeek.nl/CppGetSum.htm const int GetSum(const std::vector<int>& v) {   return std::accumulate(v.begin(),v.end(),0); }

 

 

 

 

 

The for-loop way on a std::vector<int>

 

Prefer algorithms over loops [1,2].

 

 


#include <vector> //From http://www.richelbilderbeek.nl/CppGetSum.htm int GetSum(const std::vector<int>& v) {   const int sz = static_cast<int>(v.size());   const int sum = 0;   for (int i=0; i!=sz; ++i)   {     sum+=v[i];   }   return sum; }

 

 

 

 

 

 

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