accumulate [C++ Reference]
Keywords: stl,algorithm,accumulate
Date: 2009-10-09T00:32:02-0700

[[accumulate]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- fr
- it
- jp
- pl
- ru
- tr

## 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` 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

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •