Skip to content
AgileLogics
4 min read

Ranges (C++20)

Prerequisites: Concepts (C++20)

The Ranges library composes STL-algorithm-like operations directly on a whole container, without manually threading .begin()/.end() through every call — similar in spirit to Java's streams.

#include <ranges>
#include <vector>

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

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

for (int n : evenDoubled) {
    std::cout << n << " "; // 4 8 12
}

Like STL iterators generally, a view is lazy — nothing in the pipe above actually runs until the range-based for loop iterates over it.