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?
c++stdstdvectorvector
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?
Best Answer
Actually there are quite a few methods.
C++03
Classic for loop:
Using a standard algorithm:
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
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:
Using
std::for_each
:Using a range-based for loop (thanks to Roger Pate):
C++17 and above
Using
std::reduce
which also takes care of the result type, e.g if you havestd::vector<int>
, you getint
as result. If you havestd::vector<float>
, you getfloat
. Or if you havestd::vector<std::string>
, you getstd::string
(all strings concatenated). Interesting, isn't it?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.