CodeBlanks Logo Icon CodeBlanks

Ranges

Learn composable algorithms with C++20 ranges.

Ranges

Ranges (C++20) is a composable view infrastructure in the <ranges> header. Views like std::views::filter and std::views::transform operate on a container without copying it.

The syntax is v | std::views::filter(pred) | std::views::transform(fn). The | operator chains views; each view takes the previous range as its source. The result is computed lazily during iteration, so no intermediate containers are created.

std::views::transform

std::views::transform applies a function to each element. Example: v | std::views::transform([](int x){ return x * x; }) squares each element. A filter | transform chain first filters, then transforms.

Transform does not modify the source container; it produces a new view. The view is computed during iteration, so there is no memory cost. Unlike the legacy std::transform algorithm, no intermediate container is required.

Practice Filter and transform

Create std::vector<int> v{1, 2, 3, 4, 5, 6};. Use v | std::views::filter to keep evens, then std::views::transform to map each to x * 10. Print each result via a for loop to std::cout.

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5, 6};
    // Filter and transform, then print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5, 6};
    auto r = v | std::views::filter([](int x){ return x % 2 == 0; })
               | std::views::transform([](int x){ return x * 10; });
    for (int x : r) std::cout << x;
    return 0;
}

Expected output

204060

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the chain operator

Question
auto r = v ____ std::views::filter([](int x){ return x % 2 == 0; });
Answer
auto r = v | std::views::filter([](int x){ return x % 2 == 0; });

Explanation: The | operator chains views.

2 What does std::views::filter do?

  • Keeps elements that match Correct answer
  • Transforms each element
  • Copies the container
  • Sorts the container

Explanation: filter keeps elements where the predicate is true.

3 Match the view to its purpose

Term Meaning
std::views::filter Filter by predicate
std::views::transform Map each element
std::views::take Take first n
std::views::reverse Reverse order

All lessons in Advanced