Hosted by
Hosted by RRSD


Category: algorithms Component type: function


Accumulate is an overloaded name; there are actually two accumulate functions.
template <class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init);

template <class InputIterator, class T, class BinaryFunction>
T accumulate(InputIterator first, InputIterator last, T init,
             BinaryFunction binary_op);


Accumulate is a generalization of summation: it computes the sum (or some other binary operation) of init and all of the elements in the range [first, last). [1]

The function object binary_op is not required to be either commutative or associative: the order of all of accumulate's operations is specified. The result is first initialized to init. Then, for each iterator i in [first, last), in order from beginning to end, it is updated by result = result + *i (in the first version) or result = binary_op(result, *i) (in the second version).


Defined in the standard header numeric, and in the nonstandard backward-compatibility header algo.h.

Requirements on types

For the first version, the one that takes two arguments: For the second version, the one that takes three arguments:



Linear. Exactly last - first invocations of the binary operation.


int main()
  int A[] = {1, 2, 3, 4, 5};
  const int N = sizeof(A) / sizeof(int);

  cout << "The sum of all elements in A is " 
       << accumulate(A, A + N, 0)
       << endl;

  cout << "The product of all elements in A is "
       << accumulate(A, A + N, 1, multiplies<int>())
       << endl;


[1] There are several reasons why it is important that accumulate starts with the value init. One of the most basic is that this allows accumulate to have a well-defined result even if [first, last) is an empty range: if it is empty, the return value is init. If you want to find the sum of all of the elements in [first, last), you can just pass 0 as init.

See also

inner_product, partial_sum, adjacent_difference, count

STL Main Page

Contact Us | Site Map | Trademarks | Privacy | Using this site means you accept its Terms of Use
Copyright © 2009 - 2017 Silicon Graphics International. All rights reserved.