Ranges & Views (C++20)
Range algorithms (<algorithm>, std::ranges::)
Pass the whole container instead of begin()/end():
std::ranges::sort(v);
std::ranges::find(v, 42);
std::ranges::count_if(v, pred);
Plus projections: std::ranges::sort(users, {}, &User::age);
They're also constrained with concepts → better error messages.
Views (<ranges>) — lazy, composable
A view is a lightweight, non-owning description of a sequence. Nothing is computed until you iterate.
auto big_food = expenses
| std::views::filter([](const E& e) { return e.category == "Food"; })
| std::views::transform([](const E& e) { return e.amount; })
| std::views::take(3);
for (double a : big_food) ...
The | (pipe) chains adaptors left to right.
Common view adaptors
| Adaptor | Produces |
|---|---|
views::filter(pred) | elements where pred is true |
views::transform(f) | f applied to each element |
views::take(n) / views::drop(n) | first n / skip n |
views::take_while / drop_while | based on a condition |
views::reverse | reversed order |
views::iota(a, b) | numbers a … b−1 (generated, no container) |
views::keys / views::values | from pairs/maps |
views::split(delim) | split a range |
views::enumerate (C++23) | (index, element) pairs |
views::zip (C++23) | walk several ranges together |
views::chunk(n), views::slide(n) (C++23) | groups / sliding windows |
Materializing results
std::ranges::to<std::vector>() (C++23) collects a view into a container:
auto v = some_view | std::ranges::to<std::vector>();
⚠️ Views don't own data
A view over a temporary container that's destroyed dangles. Keep the underlying container alive while using the view.
Compiler support
views::enumerate and ranges::to are C++23 — this example needs -std=c++23 (GCC 14+, recent Clang/MSVC).
Why ranges?
- Readable pipelines instead of nested loops
- No temporary containers between steps
- Lazy:
take(3)stops after 3 matches
Example
#include <algorithm>
#include <iostream>
#include <map>
#include <ranges>
#include <string>
#include <vector>
struct Expense {
std::string category;
double amount;
};
int main() {
std::vector<Expense> expenses = { { "Food", 450 }, { "Rent", 15000 }, { "Food", 1200 }, { "Travel", 300 },
{ "Food", 80 }, { "Food", 2200 }, { "Travel", 800 } };
auto food_amounts = expenses
| std::views::filter([](const Expense& e) { return e.category == "Food"; })
| std::views::transform(&Expense::amount);
std::cout << "food amounts:";
for (double a : food_amounts) std::cout << ' ' << a;
std::cout << '\n';
std::cout << "first 2 food amounts over 100:";
for (double a : food_amounts | std::views::filter([](double a) { return a > 100; }) | std::views::take(2))
std::cout << ' ' << a;
std::cout << '\n';
std::ranges::sort(expenses, std::ranges::greater{}, &Expense::amount); // projection
std::cout << "largest: " << expenses.front().category << ' ' << expenses.front().amount << '\n';
std::cout << "squares of even numbers below 10:";
for (int x : std::views::iota(1, 10) | std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; }))
std::cout << ' ' << x;
std::cout << '\n';
std::map<std::string, int> budget = { { "Bills", 3000 }, { "Food", 6000 }, { "Fun", 1500 } };
std::cout << "categories:";
for (const auto& k : budget | std::views::keys) std::cout << ' ' << k;
std::cout << "\nreversed values:";
for (int v : budget | std::views::values | std::views::reverse) std::cout << ' ' << v;
std::cout << '\n';
for (auto [i, e] : expenses | std::views::take(3) | std::views::enumerate) // C++23
std::cout << i + 1 << ". " << e.category << ' ' << e.amount << '\n';
auto travel = expenses
| std::views::filter([](const Expense& e) { return e.category == "Travel"; })
| std::views::transform(&Expense::amount)
| std::ranges::to<std::vector>(); // C++23
std::cout << "travel vector size " << travel.size() << '\n';
return 0;
}
/* Output:
food amounts: 450 1200 80 2200
first 2 food amounts over 100: 450 1200
largest: Rent 15000
squares of even numbers below 10: 4 16 36 64
categories: Bills Food Fun
reversed values: 1500 6000 3000
1. Rent 15000
2. Food 2200
3. Food 1200
travel vector size 2
*/