Standard C++ Library Class Reference
Description
accumulate applies a binary operation to init and each value in the range [first,last). The result
of each operation is returned in init. This process aggregates the result of performing the
operation on every element of the sequence into a single value.
Accumulation is done by initializing the accumulator acc with the initial value init and then
modifying it with acc = acc + *i or acc = binary_op(acc, *i) for every iterator i in the range
[first, last) in order. If the sequence is empty, accumulate returns init.
Complexity
accumulate performs exactly last-first applications of the binary operation (operator+ by
default).
Example
//
// accum.cpp
//
#include <numeric> //for accumulate
#include <vector> //for vector
#include <functional> //for times
#include <iostream.h>
int main()
{
//
//Typedef for vector iterators
//
typedef vector<int>::iterator iterator;
//
//Initialize a vector using an array of ints
//
int d1[10] = {1,2,3,4,5,6,7,8,9,10};
vector<int> v1(d1, d1+10);
//
//Accumulate sums and products
//
int sum = accumulate(v1.begin(), v1.end(), 0);
int prod = accumulate(v1.begin(), v1.end(),
1, times<int>());
//
//Output the results
//
cout << "For the series: ";