partial_sum


Fill a range with a running total.

Assign to ( result + n ) the running total first... ( first + n ) , where n = ( last - first ), and return an iterator positioned immediately after the last element in result . The first version uses operator+ to perform the summation, whereas the second version uses the binary function binary_op .

Library

Standards<ToolKit>

Declaration


#include <numeric>

template< class InputIterator, class OutputIterator >
OutputIterator partial_sum
  (
  InputIterator first,
  InputIterator last,
  OutputIterator result
  );

template
  <
  class InputIterator,
  class OutputIterator,
  class BinaryOperation
  >
OutputIterator partial_sum
  (
  InputIterator first,
  InputIterator last,
  OutputIterator result,
  BinaryOperation binary_op
  );
  

Complexity

Space complexity is constant. Time complexity is linear as ( last - first ) applications of either operator+ or binary_op are performed.

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

int numbers[ 6 ] = { 1, 2, 3, 4, 5, 6 };

void
main()
  {
  int result[ 6 ];

  partial_sum( numbers, numbers + 6, result );

  for ( int i = 0; i < 6; i ++ )
    cout << result[ i ] << ` `;
  cout << "\n";
  }

1 3 6 10 15 21
Example <ospace/osstd/examples/partsum1.cpp>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>

void
main()
  {
  vector< int > v1( 10 );
  for ( size_t i = 0; i < v1.size(); ++i )
    v1[ i ] = i;
  vector< int > v2( v1.size() );

  partial_sum( v1.begin(), v1.end(), v2.begin() );

  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";
  copy( v2.begin(), v2.end(), iter );
  cout << "\n";
  }

0 1 2 3 4 5 6 7 8 9
0 1 3 6 10 15 21 28 36 45
Example <ospace/osstd/examples/partsum2.cpp>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <vector>

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

  partial_sum( v1.begin(), v1.end(), v2.begin(), times< int >() );

  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";
  copy( v2.begin(), v2.end(), iter );
  cout << "\n";
  }

1 2 3 4 5
1 2 6 24 120

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