Syntax
std::partial_sum(first, last, output.begin());Examples
C++ prefix totals with partial_sum
Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.
#include <numeric>
#include <vector>
#include <iostream>
int main() {
std::vector<int> daily{3, 5, 2};
std::vector<int> cumulative(daily.size());
std::partial_sum(daily.begin(), daily.end(), cumulative.begin());
for (int total : cumulative) std::cout << total << ' ';
std::cout << '\n';
}- Output values: 3 8 10. Each entry includes its own day and all earlier days.
Best practices
- Allocate enough output elements. The running accumulator uses the input value type, so widening only the destination does not prevent overflow.
Runtime & versions
Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ISO C++ resources