What is std::partial_sum() in C++?

The built-in partial_sum() function is defined in the <numeric> header. The function takes partial sums of elements in an array and stores them in another array.

%0 node_1630827538423 x0 node_1630827545917 x1 node_1 x2 node_2 x3 node_3 x4

The partial sums of the array above are:

  • y0 = x0

  • y1 = x0 + x1

  • y2 = x0 + x1 + x2

  • y3 = x0 + x1 + x2 + x3

  • y4 = x0 + x1 + x2 + x3 + x4

The partial sums will then be stored in another array as shown below.

%0 node_1630827538423 y0 node_1630827545917 y1 node_1 y2 node_2 y3 node_3 y4

Syntax

partial_sum(first, last, arrayB);

Arguments

  1. first: Pointer to the first element in partial sum range (e.g., x0).
  2. last: Pointer to the last element in partial sum range (e.g., x4).
  3. arrayB: Array in which the sums are stored.

Return value

The function returns an iterator that points to past the last element that was added to arrayB.

Code

#include <iostream>
#include <numeric>
using namespace std;
int main() {
const int sizeA = 5;
int arrA[] = {1, 2, 3, 4, 5};
int arrB[sizeA];
cout << "Array A: ";
for(int i = 0; i < sizeA; i++)
{
cout << arrA[i] << " ";
}
cout << endl;
partial_sum(arrA, (arrA + sizeA), arrB);
cout << "Array B: ";
for(int i = 0; i < sizeA; i++)
{
cout << arrB[i] << " ";
}
cout << endl;
return 0;
}

Free Resources