Possible Duplicate:
sum of elements in astd::vector
I have std::vector<int>
and I want to calculate the sum of all the values in that vector.
Is there any built in function or I need to write my custom code?
Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.
Description. S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.
Which function can be used to find the sum of a vector container? Explanation: STL provides accumulate() function to find the sum of a vector.
Use the STL algorithm std::accumulate
, in the numeric
header.
#include <numeric>
// ...
std::vector<int> v;
// ...
int sum = std::accumulate(v.begin(), v.end(), 0);
accumulate(v.begin(), v.end(), 0);
Look here for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With