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?
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?
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);
You would need to make your own custom code.
int sum = 0; for (int i = 0; i < myvector.size(); i++) sum += myvectory[i];
The answer is in the variable 'sum'.