Math-Linux.com

Knowledge base dedicated to Linux and applied mathematics.

Home > C++ > FAQ C++ > FAQ C++ - STL > How to sum elements of a C++ std::vector ?

How to sum elements of a C++ std::vector ?

How to sum elements of a C++ std::vector ?

You must include the following header:

#include <numeric>

We use

template <class InputIterator, class T>
  T accumulate ( InputIterator first, InputIterator last, T init );

It returns accumulating all the values in the range [first,last] to init.

For example

#include<vector>
#include<iostream>
#include<numeric>

using namespace std;
int main (void)
{
vector<int> u(3,0);
u[0]=78;
u[2]=-53;
int sum = std::accumulate(u.begin(),u.end(),0);
cout << "Sum:=" << sum << endl;
}
Sum:=25

Any message or comments?

comments powered by Disqus