liveBook · Manning

Std::views::transform

As explained in 100 C++ Mistakes and How to Avoid Them

std::views::transform is a C++ standard-library range adaptor that lazily maps each element of a range through a supplied function.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines one-to-one mapping and demonstrates composition, without detailing adaptor internals.
Examples
Demonstrates absolute-value transformation followed by even-value filtering and accumulation.
What it assumes
Assumes familiarity with sequences and functions while distinguishing mapping from filtering and reduction.
What you can do after
Apply it via the C++ ranges pipeline syntax to transform values before other range operations.
How it connects
Connects mapping with ranges, range adaptors, filtering, predicates, reduction, and lambdas.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.