C++ Numeric Library - partial_sum


Advertisements

Description

It is used to compute partial sums of range and assigns to every element in the range starting at result the partial sum of the corresponding elements in the range [first,last).

Declaration

Following is the declaration for std::partial_sum.

C++98

	
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);

C++11

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);
  • first, last − It iterators to the initial and final positions in a sequence.

  • init − It is an initial value for the accumulator.

  • binary_op − It is binary operation.

  • binary_op2 − It is binary operation and taking two elements.

Return Value

It returns an iterator pointing to past the last element of the destination sequence where resulting elements have been stored, or result if [first,last) is an empty range.

Exceptions

It throws if any of the operations on the elements or iterators throws.

Data races

The elements in the range [first1,last1) are accessed.

Example

In below example for std::partial_sum.

#include <iostream>
#include <functional>
#include <numeric>

int myop (int x, int y) {return x+y+1;}

int main () {
   int val[] = {10,20,30,40,50};
   int result[5];

   std::partial_sum (val, val+5, result);
   std::cout << "Default partial_sum: ";
   for (int i=0; i<5; i++) std::cout << result[i] << ' ';
   std::cout << '\n';

   std::partial_sum (val, val+5, result, std::multiplies<int>());
   std::cout << "Functional operation multiplies: ";
   for (int i=0; i<5; i++) std::cout << result[i] << ' ';
   std::cout << '\n';

   std::partial_sum (val, val+5, result, myop);
   std::cout << "Custom function: ";
   for (int i=0; i<5; i++) std::cout << result[i] << ' ';
   std::cout << '\n';
   return 0;
}

The output should be like this −

Default partial_sum: 10 30 60 100 150 
Functional operation multiplies: 10 200 6000 240000 12000000 
Custom function: 10 31 62 103 154 
numeric.htm
Advertisements