HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How to sum up elements of a std::vector?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howstdsumvectorelements

Problem

What are the good ways of finding the sum of all the elements in a std::vector?

Suppose I have a vector std::vector vector with a few elements in it. Now I want to find the sum of all the elements. What are the different ways for the same?

Solution

Actually there are quite a few methods.

int sum_of_elems = 0;


C++03

-
Classic for loop:

for(std::vector::iterator it = vector.begin(); it != vector.end(); ++it)
     sum_of_elems += *it;


-
Using a standard algorithm:

#include 

 sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);


Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0 to 0.0 or 0.0f (thanks to nneonneo). See also the C++11 solution below.

C++11 and higher

-
b. Automatically keeping track of the vector type even in case of future changes:

#include 

 sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                decltype(vector)::value_type(0));


-
Using std::for_each:

std::for_each(vector.begin(), vector.end(), [&] (int n) {
     sum_of_elems += n;
 });


-
Using a range-based for loop (thanks to Roger Pate):

for (auto& n : vector)
     sum_of_elems += n;


C++17 and above

-
Using std::reduce which also takes care of the result type, e.g if you have std::vector, you get int as result. If you have std::vector, you get float. Or if you have std::vector, you get std::string (all strings concatenated). Interesting, isn't it?

#include        

auto result = std::reduce(v.begin(), v.end());


There are other overloads of this function which you can run even parallelly, in case if you have a large collection and you want to get the result quickly.

Code Snippets

int sum_of_elems = 0;
for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
     sum_of_elems += *it;
#include <numeric>

 sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
#include <numeric>

 sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                decltype(vector)::value_type(0));
std::for_each(vector.begin(), vector.end(), [&] (int n) {
     sum_of_elems += n;
 });

Context

Stack Overflow Q#3221812, score: 628

Revisions (0)

No revisions yet.