12

Possible Duplicate:
sum of elements in a std::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?

Community
  • 1
  • 1
Jame
  • 19,728
  • 34
  • 77
  • 103

3 Answers3

32

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);
John Calsbeek
  • 35,189
  • 7
  • 91
  • 100
11

accumulate(v.begin(), v.end(), 0);

Look here for more details.

Petar Minchev
  • 45,963
  • 11
  • 102
  • 118
1

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'.

thephpdev
  • 29
  • 1