Mastering std::transform_exclusive_scan: Tips and Code Examples

2025-08-29

First, a quick refresher. std::transform_exclusive_scan is an algorithm that combines two operations

It applies a unary transformation function to each element of a range.

Then, it performs an exclusive scan (a prefix sum) on the transformed elements.

The "exclusive" part means that each output element is the sum of all previous transformed elements, not including the current one. The first output element is always the initial value you provide.

This is probably the most frequent issue. Because std::transform_exclusive_scan is an exclusive scan, the output range needs to be able to hold one more element than the input range if you want to see a result for every input element.

Problem
You forget this and use a destination container of the same size as the source.

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

int main() {
    std::vector<int> input = {1, 2, 3, 4};
    std::vector<int> output(input.size()); // Problem: Same size!

    std::transform_exclusive_scan(
        input.begin(),
        input.end(),
        output.begin(),
        0,
        std::plus<int>(),
        [](int x){ return x * 2; }
    );

    // The last element of 'output' will be garbage or a copy of an input element.
    // What was expected: {0, 2, 6, 12, 20}
    // What you might see: {0, 2, 6, 12} with a garbage value
    for (int val : output) {
        std::cout << val << " ";
    }
    std::cout << std::endl;
    return 0;
}

Solution
Make sure your output container is large enough! A common way to handle this is to use std::back_inserter.

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>

int main() {
    std::vector<int> input = {1, 2, 3, 4};
    std::vector<int> output; // Let's use a dynamic container

    std::transform_exclusive_scan(
        input.begin(),
        input.end(),
        std::back_inserter(output), // Solution: Use back_inserter!
        0,
        std::plus<int>(),
        [](int x){ return x * 2; }
    );

    for (int val : output) {
        std::cout << val << " ";
    }
    std::cout << std::endl; // Output: 0 2 6 12
    return 0;
}

Wait, that's not what we expected! The std::back_inserter version gives an output of size 4. This is because the exclusive scan's result for the last element is the sum of all elements before it. The total sum, 2+4+6+8 = 20, is what would be the fifth element. Since back_inserter only adds elements as the algorithm provides them, you get the correct output for the first four elements.

To get the "full" result of size 5 (including the total sum), you'd need to resize your vector explicitly

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

int main() {
    std::vector<int> input = {1, 2, 3, 4};
    std::vector<int> output(input.size() + 1); // Correct size!

    std::transform_exclusive_scan(
        input.begin(),
        input.end(),
        output.begin(),
        0,
        std::plus<int>(),
        [](int x){ return x * 2; }
    );

    for (int val : output) {
        std::cout << val << " ";
    }
    std::cout << std::endl; // Output: 0 2 6 12 20
    return 0;
}

The std::transform_exclusive_scan algorithm's second-to-last argument is a binary operation (like std::plus) that combines the transformed elements. If you use the wrong one, you get unexpected results.

Problem
You want to find the maximum value so far, but you use std::plus.

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

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

    std::transform_exclusive_scan(
        input.begin(),
        input.end(),
        output.begin(),
        0,
        std::plus<int>(), // Problem: Using plus when you want max!
        [](int x){ return x; } // A simple identity transform
    );

    // This will give a running sum: {0, 3, 4, 8, 9}
    // But maybe you wanted a running max: {0, 3, 3, 4, 4}
    for (int val : output) {
        std::cout << val << " ";
    }
    std::cout << std::endl;
    return 0;
}

Solution
Use the correct binary operation, like std::max.

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

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

    std::transform_exclusive_scan(
        input.begin(),
        input.end(),
        output.begin(),
        0,
        [](int a, int b){ return std::max(a, b); }, // Solution: Use a lambda for max!
        [](int x){ return x; }
    );

    for (int val : output) {
        std::cout << val << " ";
    }
    std::cout << std::endl; // Output: 0 3 3 4 4
    return 0;
}

Sometimes, std::transform_exclusive_scan might be a little too specific for what you need. Here are some alternatives.

If you only want to apply a function to a range and store the results, without any prefix sum, std::transform is the way to go. It's simpler and more direct.

#include <iostream>
#include <vector>
#include <algorithm>

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

    std::transform(
        input.begin(),
        input.end(),
        output.begin(),
        [](int x){ return x * 2; } // Just the transformation
    );

    for (int val : output) {
        std::cout << val << " ";
    }
    std::cout << std::endl; // Output: 2 4 6 8
    return 0;
}

If the transformation is an identity (i.e., you're not changing the elements before scanning), std::exclusive_scan is a simpler, more readable choice.

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

int main() {
    std::vector<int> input = {1, 2, 3, 4};
    std::vector<int> output(input.size() + 1);

    std::exclusive_scan(
        input.begin(),
        input.end(),
        output.begin(),
        0,
        std::plus<int>() // Just the scan part
    );

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

cpp



Efficient C++ Vector Insertion: A Guide to std::vector::insert

First, let's quickly review what std::vector::insert does. It allows you to insert new elements into a vector at a specific position


Mastering C++ ofstream: A Guide to is_open() and Alternatives

std::basic_ofstream::is_open is a member function that checks if a file stream is currently associated with a physical file


std::make_tuple vs. std::tuple: When to Use Each in C++

std::make_tuple is a fantastic tool for creating a std::tuple object, but it's important to understand how it works to avoid common pitfalls



A Friendly Guide to C++ Coroutines: Mastering the co_return Keyword

Let's dive into the co_return keyword in C++.In C++, co_return is a keyword used exclusively within a coroutine. Think of a coroutine as a special kind of function that can be paused and resumed


C++ std::span::empty() Explained: Common Traps and Best Practice Code Samples

The std::span::empty() method is used to check if the std::span is empty (i.e., whether it holds zero elements). It returns true if the span's size is zero


C++ Memory Alignment: Pitfalls and Solutions with std::max_align_t

std::max_align_t is a type defined in the C++ <cstddef> header. Its main job is to represent the largest, most fundamental alignment requirement for any object type


Common Issues and Alternatives for std::chrono::round

The std::chrono::round function, available since C++17, rounds a std::chrono::time_point or a std::chrono::duration to the nearest value of a specified duration


A Guide to Hashing std::chrono::year_month_weekday in C++

The most common issue with std::hash is that it might not be supported on all compilers, especially older ones. The std::chrono library


Common Issues with std::islessequal in C++ and How to Avoid Them

Since it's not a Numerics function, I will focus on the floating-point comparison aspect and provide some friendly advice


Problem/Solution Focus

Since std::ranges::enumerate_view is a C++23 feature, the documentation on its private members might be a bit sparse, but we can infer its purpose and discuss common pitfalls and alternatives based on the Ranges concept and the enumerate_view's goal