C++ Basics: Build Prefix Totals with partial_sum
Turn a sequence of daily counts into cumulative totals without writing a manual accumulation loop.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as partial-sum-prefix-totals-demo.cpp:
#include <array>
#include <iostream>
#include <numeric>
int main() {
const std::array<long long, 4> daily_counts{3, 5, 2, 4};
std::array<long long, 4> cumulative_counts{};
std::partial_sum(daily_counts.begin(), daily_counts.end(),
cumulative_counts.begin());
std::cout << "Cumulative counts:";
for (long long count : cumulative_counts) {
std::cout << ' ' << count;
}
std::cout << '\n';
const long long middle_days = cumulative_counts[2] - cumulative_counts[0];
std::cout << "Days 2 through 3: " << middle_days << '\n';
}Compile and run it. The second command runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic partial-sum-prefix-totals-demo.cpp -o partial-sum-prefix-totals-demo &&
./partial-sum-prefix-totals-demoObserved output:
Cumulative counts: 3 8 10 14
Days 2 through 3: 7Read the result
Each output includes the corresponding input and every earlier count. The third prefix is 10. Subtracting the first prefix, 3, leaves 7 for the second and third days. These are inclusive prefixes; the first output is the first input, not zero.
Apply it carefully
partial_sum uses the input value type for its internal accumulator. A wider output container alone does not prevent overflow, so the example stores the input as long long too. Real counts still need range checks if totals may exceed that type. Ensure the output range has enough elements. Empty input produces no totals; do not index an empty result.
The C++ working draft describes the relevant library rules. This example uses only C++20 facilities, even though the linked draft also documents newer additions.
Clean up
Remove only the source and executable created here, then remove the empty practice directory:
rm -- partial-sum-prefix-totals-demo.cpp partial-sum-prefix-totals-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.