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

Also in this section

  1. How to print the elements of a C++ std::vector with GNU Debugger GDB ?
  2. How to convert string to lower case or UPPER case in C++ ?
  3. How to get command-line parameters in a C++ vector<string> ?
  4. How to split a string in C++ using STL ?
  5. How to sum elements of a C++ std::vector ?