accumulate

Syntax:

    #include <numeric>
    TYPE accumulate( iterator start, iterator end, TYPE val );
    TYPE accumulate( iterator start, iterator end, TYPE val, BinaryFunction f );

The accumulate function computes the sum of val and all of the elements in the range [start,end).

If the binary function f if specified, it is used instead of the + operator to perform the summation.

The accumulate function runs in linear time.

For example, the following code uses accumulate to sum the integers in a vector:

#include <iostream>
using std::cout;
#include <vector>
using std::vector;
#include <numeric>
using std::accumulate;
 
int main() {
  vector<int> v;
  const int START = 1, END = 10;
  for( int i = START; i <= END; ++i ) v.push_back(i);
 
  int sum = accumulate( v.begin(), v.end(), 0 );
 
  cout << "sum from " << START << " to " << END << " is " << sum << '\n';
}

Related Topics: adjacent_difference, count, inner_product, partial_sum