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
  • 21,150
  • 37
  • 80
  • 107

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);
Delgan
  • 18,571
  • 11
  • 90
  • 141
John Calsbeek
  • 35,947
  • 7
  • 94
  • 101
11

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

Look here for more details.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
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