std::views::transform maps every input element through a supplied function and produces one corresponding output element. It composes naturally with other range operations. section 4.4
Use transform when:
- You need to convert values without changing the sequence length, such as mapping negative numbers to their absolute values. section 4.4
- You want to feed transformed values into a filter or reduction within one composed range pipeline. section 4.4
Listing 4.9 Composed functions on a value sequence
int main() {
std::vector<int> vals { 42, 3, 7 -9, 0, 22, 23, -7, 22 };
auto evens = vals
| std::views::transform([](int x) { return abs(x); })
| std::views::filter([](int x){ return x % 2 == 0; }); #1
auto sum = std::accumulate(evens.begin(), evens.end(), 0); #2
std::cout << sum << '\n';
return 0;
}
A composed pipeline transforms values to absolute values, filters the even results, and accumulates the remaining sequence. section 4.4
