How to Sum up Elements of a C++ Vector?
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...
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?
13 Answers
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 floating-point numbers, change
0to0.0or0.0f(thanks to nneonneo). See also the C++11 solution below.