2

Possible Duplicate:
sum of elements in a std::vector

I want to sum the items of a std::vector

For example

 std::vector<int > MYvec;
 /*some push backs*/

 int x=sum(MYVec); //it should give sum of all the items in the vector

How to write sum function?

I have tried this

 int sum(const std::vector<int> &Vec)
 {
    int result=0;
    for (int i=0;i<Vec.size();++i)
      result+=Vec[i];
    return result;
 }

However I don't like my approach

Community
  • 1
  • 1
ramakrishna
  • 21
  • 1
  • 2

4 Answers4

8

Try to use accumulate from C++ standard library. Something like this:

#include <vector>
#include <numeric>

// Somewhere in code...
std::vector<int> MYvec;
/*some push backs*/

int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );
Roman Hwang
  • 405
  • 5
  • 10
2

You should use std::accumulate.

int main() {
  std::vector<int> vec;
  // Fill your vector the way you like
  int sum = std::accumulate(vect.begin(), vect.end(), 0); // 0 is the base value
  std::cout << sum << std::endl;
  return 0;
}
Opera
  • 983
  • 1
  • 6
  • 17
1

Isent there a std::accumulate function that does this?

InsertNickHere
  • 3,616
  • 3
  • 26
  • 23
  • Almost. `std::accumulate` uses `operator+`, not `operator+=`. But in any sane program, that should not make a difference, and with `int`s it definitely doesn't. – Thomas Aug 07 '10 at 10:28
0

You have to iterate over all the items in the array and compute the sum, there is no easier way. I guess for cycle is the simplest

int sum = 0;
for(unsigned i = 0; i < Myvec.size(); i++){
   sum += MYvec[i];
}
Matěj Zábský
  • 16,909
  • 15
  • 69
  • 114