Vector amount in C ++ design strategy

Possible duplicate:
sum of elements instd::vector

I want to sum the std :: vector elements

for instance

 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 a function sum?

I 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

+3
source share
4 answers

Try using accumulate from the C ++ standard library. Something like that:

#include <vector>
#include <numeric>

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

int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );
+8
source

You must 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;
}
+2
source

Isent std:: accumulate, ?

+1

, . ,

int sum = 0;
for(unsigned i = 0; i < Myvec.size(); i++){
   sum += MYvec[i];
}
0

Source: https://habr.com/ru/post/1758511/


All Articles