accumulate

Syntax:

#include <numeric>
TYPE accumulate( input_iterator start, input_iterator end, TYPE val );
TYPE accumulate( input_iterator start, input_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 is 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';
}

The accumulate function can also be used on non-numerical types. The following example uses accumulate to concatenate all of the strings in a vector into a single string:

int main () {
    string str = "Hello World!";
    vector<string> vec(10,str);   // vec = ["Hello World!", "Hello World!", ...]
    string a = accumulate( vec.begin(), vec.end(), string("") );
    cout << a << endl;            // displays "Hello World!Hello World!Hello..."
}

Related Topics: adjacent_difference, count, inner_product, partial_sum