C++C++
AdvancedLesson 16 of 18

Ranges and Concepts (C++20) – C++

Readable data pipelines with views and templates with clear requirements.

Ranges (<ranges>) connect containers and algorithms elegantly. Views are lazy: they compute elements only when iterated and copy nothing. With | you build pipelines.

#include <iostream>
#include <ranges>
#include <vector>

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

    for (int x : ergebnis) std::cout << x << ' ';      // 4 16 36 64 100
    std::cout << '\n';
}

The algorithms in the namespace std::ranges accept a container directly instead of two iterators; std::views::iota generates number sequences:

#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> v{5, 3, 8, 1};
    std::ranges::sort(v);                          // instead of sort(v.begin(), v.end())
    std::ranges::sort(v, std::greater{});          // descending
    for (int x : v) std::cout << x << ' ';         // 8 5 3 1
    std::cout << '\n';

    for (int i : std::views::iota(1, 6) | std::views::reverse)
        std::cout << i << ' ';                     // 5 4 3 2 1
    std::cout << '\n';
}

Concepts describe what a template type must be able to do. If a type violates them, the compiler reports a clear error message at the call site instead of pages of instantiation errors.

#include <concepts>
#include <iostream>

template <std::integral T>
T doppelt(T x) { return x * 2; }

template <typename T>
concept Druckbar = requires(T t, std::ostream& os) { os << t; };

template <Druckbar T>
void zeige(const T& t) { std::cout << t << '\n'; }

int main() {
    std::cout << doppelt(21) << '\n';     // 42
    zeige("Hello");
    // doppelt(2.5);                      // error: double does not satisfy std::integral
}
TipYou find predefined concepts such as std::integral, std::floating_point, std::totally_ordered or std::invocable in <concepts>. You can also write requires clauses directly after the template parameter list.
WarningViews hold no data of their own. A view over a temporary container or a vector that has since been destroyed points into nothing (dangling). Build pipelines only over containers that live long enough.