CKTIS / C++
std::ranges::transform — transform elements into an output
std::ranges::transform computes values from one range or corresponding elements of two ranges and writes them through an output iterator. It is an eager algorithm, not a lazy view.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::ranges::transform(r, out, op);
std::ranges::transform(r, out, op, proj);
std::ranges::transform(first, last, out, op, proj);
std::ranges::transform(r1, r2, out, binary_op);
std::ranges::transform(r1, r2, out, binary_op, proj1, proj2);
std::ranges::transform(first1, last1, first2, last2, out, binary_op, proj1, proj2);std::ranges::transform from <algorithm> accepts ranges or iterator–sentinel pairs. The unary form transforms every element; the binary form combines corresponding elements and stops at the shorter input. Optional projections proj, proj1, proj2 are applied before the operation; by default they leave arguments unchanged.
The output must support writing every result. The algorithm does not grow a container: reserve() alone does not create elements. Provide existing elements or use std::back_inserter with a suitable container. In-place transformation is allowed when output starts at the beginning of an input. The operation itself must not modify range elements or invalidate iterators.
The result exposes final positions as .in and .out, or .in1, .in2, and .out. For a temporary non-borrowed range, an input field can have type std::ranges::dangling. For N written results, the operation and each projection are invoked exactly N times.
Unlike lazy std::views::transform, this algorithm writes results before returning. This entry describes C++23 usage; the current working draft also contains later extensions. A repository compiler flag does not attest production runtime compatibility.
Examples
#include <algorithm>
#include <array>
#include <iostream>
int main() {
const std::array<int, 4> input{1, 2, 3, 4};
std::array<int, 4> output{};
auto result = std::ranges::transform(
input, output.begin(), [](int x) { return x * x; });
for (auto it = output.begin(); it != result.out; ++it) {
if (it != output.begin()) std::cout << ' ';
std::cout << *it;
}
std::cout << '\n';
}
Result
1 4 9 16
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.