# (C++) GetSum (on a container)

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 #include #include //From http://www.richelbilderbeek.nl/CppGetSum.htm template const T::value_type GetSum(const T& v) {   return std::accumulate(v.begin(), v.end(), static_cast(0.0)); } ```

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

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

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

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