C++ Basics: Combine Two Ranges with a Bounded Transform
Use the C++20 ranges overload of transform to combine two inputs and stop when either ends. This is useful for pairwise calculations on separately collected readings.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus 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 transform-two-input-lengths-demo.cpp:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> prices{10, 20, 30};
std::vector<int> quantities{2, 3};
std::vector<int> totals;
auto result = std::ranges::transform(prices, quantities,
std::back_inserter(totals), [](int a, int b) { return a * b; });
std::cout << "totals:";
for (int value : totals) std::cout << ' ' << value;
std::cout << '\n';
std::cout << "prices consumed: " << result.in1 - prices.begin() << '\n';
std::cout << "quantities consumed: " << result.in2 - quantities.begin() << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic transform-two-input-lengths-demo.cpp -o transform-two-input-lengths-demo &&
./transform-two-input-lengths-demoObserved output:
totals: 20 60
prices consumed: 2
quantities consumed: 2Read the result
Only two products are produced. The returned input iterators both report two consumed elements; the third price has no matching quantity.
Apply it carefully
Stopping at the shorter range prevents this particular length overrun, but it can hide missing business data. Validate equal sizes first when every price must have a quantity. The older binary std::transform overload with only one input end iterator requires the second input to be long enough. Integer multiplication must still stay within the result type.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- transform-two-input-lengths-demo.cpp transform-two-input-lengths-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.