C++ Numeric::partial_sum() function
The C++ std::numeric::partial_sum() function is used to return the partial sums of the range of elements. It processes a sequence of numbers and produces a new sequence where each element is the cumulative sum of the elements up to that point. It also accepts a binary operation form custom accumulation.
Syntax
Following is the syntax for std::numeric::partial_sum() function.
OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result); or OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op);
Parameters
- first, last − It indicates the iterators to the initial and final positions in a sequence.
- result − It is an output iterator to the initial position in the destination sequence where the partial sum is stored.
- binary_op − It is binary operation.
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 1
In the following example, we are going to consider the basic usage of the partial_sum() function.
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector < int > x = {2,4,6};
std::vector < int > y(3);
std::partial_sum(x.begin(), x.end(), y.begin());
for (int x: y)
std::cout << x << " ";
return 0;
}
Output
Output of the above code is as follows −
2 6 12
Example 2
Consider the following example, where we are going to use perform the simple addition with partial_sum().
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector < int > x = {1,3,5};
std::vector < int > y(x.size());
std::partial_sum(x.begin(), x.end(), y.begin());
for (int a: y)
std::cout << a << " ";
return 0;
}
Output
Following is the output of the above code −
1 4 9
Example 3
Let's look at the following example, where we are going to perform the cumulative subtraction.
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector < int > a = {2,4,6};
std::vector < int > b(a.size());
std::partial_sum(a.begin(), a.end(), b.begin(), std::minus < int > ());
for (int x: b)
std::cout << x << " ";
return 0;
}
Output
If we run the above code it will generate the following output −
2 -2 -8