How to sum up elements of a C++ vector?
Posted By: Anonymous
What are the good ways of finding the sum of all the elements in a std::vector
?
Suppose I have a vector std::vector<int> 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<int>::iterator it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it;

Using a standard algorithm:
#include <numeric> 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 floatingpoint numbers, change
0
to0.0
or0.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 <numeric> 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 rangebased for loop (thanks to Roger Pate):
for (auto& n : vector) sum_of_elems += n;
Answered By: Anonymous
Disclaimer: This content is shared under creative common license ccbysa 3.0. It is generated from StackExchange Website Network.