tags:

views:

111

answers:

4

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

A: 

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];
}
CommanderZ
+1  A: 

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

InsertNickHere
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
+2  A: 

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
+6  A: 

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
Remember to `#include <algorithm>`.
Thomas
Thank, good point, Thomas.
Roman Hwang
`accumulate` comes from the `<numeric>` header.
UncleBens
See Prasoon's answer http://stackoverflow.com/questions/3221812/sum-of-elements-in-a-stdvector/3221813#3221813
Shekhar Gupta
@UncleBens thanks, corrected.
Roman Hwang