accumulate


Sum the values in a range.

Add the value of each element in the range [ first, last ) to init and return the new value of init . The variable init is not automatically initialized prior to this operation. The first version uses operator+ to perform the addition, whereas the second version uses the binary function binary_op .

Library

Standards<ToolKit>

Declaration


#include <numeric>

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

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

Complexity

Time complexity is linear. Space complexity is constant.

Example <ospace/osstd/examples/accum1.cpp>
#include <iostream>
#include <vector>
#include <numeric>

void
main()
  {
  vector< int > v( 5 );
  for ( size_t i = 0; i < v.size(); ++i )
    v[ i ] = i + 1;

  int sum = accumulate( v.begin(), v.end(), 0 );

  cout << "Sum = " << sum << endl;
  }

Sum = 15
Example <ospace/osstd/examples/accum2.cpp>
#include <iostream>
#include <vector>
#include <numeric>

mult( int initial, int element )
  {
  return initial * element;
  }

void
main()
  {
  vector< int > v( 5 );
  for ( size_t i = 0; i < v.size(); ++i )
    v[ i ] = i + 1;

  int prod = accumulate( v.begin(), v.end(), 1, mult ) ;

  cout << "prod = " << prod << "\n";
  }

Prod = 120

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.