The C++ std::partial_sum Function: A Practical Tutorial

2025-09-17

The std::partial_sum function in C++ is a powerful tool for calculating prefix sums (also known as a running total). It iterates through a range of elements and, for each element, computes the sum of all preceding elements plus itself. Think of it like keeping a running tally of your scores in a game—each new score is added to the total of all previous scores.

The function takes at least two iterators

The input iterator, which points to the beginning of the range you want to sum up.

The output iterator, which points to where you want the resulting partial sums to be stored.

For example, if you have a vector of numbers [1, 2, 3, 4], std::partial_sum will produce a new sequence [1, 3, 6, 10].

This is a very common mistake. If you use the same container for both the input and the output, you can get unexpected results. The algorithm modifies the container in place, which means the input values change as the calculation proceeds.

Problem
Using the same vector for both input and output.

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    
    // BAD: The output will overwrite the input, leading to incorrect results
    std::partial_sum(nums.begin(), nums.end(), nums.begin()); 

    for (int n : nums) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    // Expected: 1 3 6 10 15
    // Actual (for some implementations): might be something different
    return 0;
}

Solution
Always use a separate container for the output. This ensures the input data remains unchanged and the calculation is correct. You can pre-allocate the output container to the correct size.

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    std::vector<int> partial_sums(nums.size()); // Create a new vector for the result

    // GOOD: The output goes into a separate container
    std::partial_sum(nums.begin(), nums.end(), partial_sums.begin());

    for (int n : partial_sums) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    // Output: 1 3 6 10 15
    return 0;
}

By default, std::partial_sum uses operator+ for the sum. If you're working with custom objects or need a different operation (like multiplication), you'll need to provide a custom binary operation.

Problem
Trying to sum a non-numeric type without a custom operation.

#include <iostream>
#include <vector>
#include <numeric>

struct MyStruct {
    int value;
};

int main() {
    std::vector<MyStruct> data = {{1}, {2}, {3}};
    std::vector<MyStruct> sums(data.size());

    // This will cause a compiler error because MyStruct doesn't have operator+ defined
    // std::partial_sum(data.begin(), data.end(), sums.begin()); 
    return 0;
}

Solution
Provide a custom binary operation as a third argument. This can be a lambda function, a function object, or a regular function.

#include <iostream>
#include <vector>
#include <numeric>

struct MyStruct {
    int value;
};

int main() {
    std::vector<MyStruct> data = {{1}, {2}, {3}};
    std::vector<int> sums(data.size());

    // GOOD: Use a lambda to specify how to "sum" the structs
    // The lambda takes the running total and the current element, and returns the new total.
    std::partial_sum(data.begin(), data.end(), sums.begin(),
        [](int total, const MyStruct& current) {
            return total + current.value;
        });

    for (int n : sums) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    // Output: 1 3 6
    return 0;
}

While std::partial_sum is the standard way to do this, sometimes you might prefer a manual loop for simplicity or to have more control over the process.

A simple for loop is often the most readable alternative, especially for smaller projects or for those who are less familiar with standard algorithms.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    std::vector<int> partial_sums(nums.size());

    int current_sum = 0;
    for (size_t i = 0; i < nums.size(); ++i) {
        current_sum += nums[i];
        partial_sums[i] = current_sum;
    }

    for (int n : partial_sums) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    // Output: 1 3 6 10 15
    return 0;
}

This approach is clear and direct. You explicitly declare a variable to hold the running total and update it in each iteration.

This is a more advanced example that shows how std::partial_sum can be used with a custom operator+. This is a good practice if your custom type represents a quantity that naturally has an addition operation.

#include <iostream>
#include <vector>
#include <numeric>

struct Point {
    int x, y;
    // Overload the + operator
    Point operator+(const Point& other) const {
        return {x + other.x, y + other.y};
    }
};

int main() {
    std::vector<Point> points = {{1, 1}, {2, 2}, {3, 3}};
    std::vector<Point> partial_points(points.size());

    // Now std::partial_sum works directly!
    std::partial_sum(points.begin(), points.end(), partial_points.begin());

    for (const auto& p : partial_points) {
        std::cout << "(" << p.x << ", " << p.y << ") ";
    }
    std::cout << std::endl;
    // Output: (1, 1) (3, 3) (6, 6) 
    return 0;
}

In this case, std::partial_sum "just works" because you've taught the Point class how to add itself to another Point.


cpp



How to Safely Use std::ranges::reverse_view in C++

In C++, std::ranges::reverse_view is a view adapter that presents the elements of a range in reverse order without actually modifying the original data


A Developer's Guide to C++ Character Encoding Beyond std::codecvt

Hey there! Let's dive into some common issues with std::codecvt::do_in and check out some great alternatives. This function is a bit tricky


Going Backwards in C++: A Friendly Guide to the ReversibleContainer Concept

I'll explain what it is, some common problems people run into, and provide clear sample code for common alternative approaches



Resolving Locale and Overflow Errors with std::to_wstring

The std::to_wstring function is useful for converting numerical values into a std::wstring. However, developers often encounter a few common issues


A Developer's Guide to C++ zip_view::iterator::operator[]

First off, let's break down what this operator does and when it's available.A std::ranges::zip_view combines multiple ranges (like $\text{std}\text{vector}$s or other views) into a single


Common C++ I/O Issues with std::basic_iostream

You'll most often use its two specializationsstd::iostream for character I/O.std::wcout for wide character I/O.When you use std::cin or std::cout


std::fill_n: Common Issues and Alternatives

std::fill_n is a handy function for filling a sequence with a specific value, but it's not without its gotchas. The most common issues revolve around the iterator and count


A Guide to Using and Avoiding Pitfalls with C++ Stack Trace Operator[]

Instead of focusing on non-existent "common troubles, " let's break down the function and its usage with examples. This will help you understand how it works and avoid any potential pitfalls


Beyond std::range_formatter: C++ Alternatives for Range Formatting

The std::range_formatter is a powerful tool in C++20 for easily formatting ranges (like std::vector, std::list, etc. ) for output


Mastering std::ranges::take_view::size: Common Pitfalls and Alternatives

The main issue people run into is a compile-time error. This happens because std::ranges::take_view::size is only available if the underlying range has a size() member function that provides an O(1) complexity