CKTIS / C++
Filtering and transforming ranges
Combine std::views::filter and std::views::transform to select range elements and compute new values. The pipeline creates a lazy view rather than a ready-made container of results.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
range | std::views::filter(predicate) | std::views::transform(function)Filtering and transformations are two distinct operations on a range. std::views::filter(predicate) exposes elements satisfying a predicate, preserving their order. std::views::transform(function) exposes the result of calling a function for each element; it does not itself discard elements. Both adaptors are available in <ranges>.
The | operator connects stages: range | std::views::filter(predicate) | std::views::transform(function) selects elements first, then transforms them. Order matters: reversing the stages makes the predicate receive transformed results rather than original elements.
The result is a lazy view, not a new container. The predicate runs while searching for matching elements, and the transformation function runs when an iterator's element is read. Do not assume exactly one function call per element or cached transformation results. Use functions without side effects. In the example, the view refers to numbers, so that container must remain alive during iteration; the pipeline itself does not change it.
The example selects 2, 4, 6 and prints their squares: 4, 16, 36, one per line. It uses C++23 mode. The supplied source is an evolving working draft, not a frozen C++23 text; production runtime support has not been attested.
Examples
#include <iostream>
#include <ranges>
#include <vector>
int main() {
const std::vector<int> numbers{1, 2, 3, 4, 5, 6};
auto result = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
for (int value : result) {
std::cout << value << '\n';
}
}
Result
4 16 36
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.