C++20 Ranges & Composable Views

🔴 Advanced

📖 Definition

Introduced in ISO C++20, the Ranges library (in <ranges>) allows composing lazy, zero-allocation algorithms using pipe syntax (std::views::filter | std::views::transform).

💡 Code Example (C++20)

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

int main() {
    std::vector<int> nums{1, 2, 3, 4, 5, 6};

    auto evenSq = nums
        | std::views::filter([](int n) { return n % 2 == 0; })
        | std::views::transform([](int n) { return n * n; });

    for (int n : evenSq) {
        std::cout << n << " "; // 16 36
    }
    std::cout << "\n";
    return 0;
}