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.
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.
Syntax
partial_sum(first, last, arrayB);
Arguments
first: Pointer to the first element in partial sum range (e.g., x0).last: Pointer to the last element in partial sum range (e.g., x4).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;}