A range is anything with a begin() and an end(), such as a container. The ranges library builds on this with:
- Range algorithms: take the whole range instead of two iterators.
- Views: change how a range is seen without copying it.
Range algorithms are in the std::ranges#include <ranges> namespace and the algorithm header:
#include <algorithm>
std::vector#include <vector><int> v = {3, 1, 4, 1, 5};
std::ranges::sort#include <algorithm>(v); // {1, 1, 3, 4, 5}
std::ranges::count#include <algorithm>(v, 1); // 2
std::ranges::find#include <algorithm>(v, 4); // Points to 4.Range algorithms also take a projection, which is applied to each element before it is compared. This sorts by a field without writing a comparison lambda:
struct Person {
std::string#include <string> name;
int age;
};
std::vector#include <vector><Person> people = {{"Alice", 30}, {"Bob", 25}};
// {} keeps the default comparison.
std::ranges::sort#include <algorithm>(people, {}, &Person::age); // Bob, then Alice.A view is a lightweight range that refers to another range and changes how its elements are seen. Views are in the std::views#include <ranges> namespace and the ranges header:
#include <ranges>
std::vector#include <vector><int> v = {1, 2, 3, 4, 5};
auto is_even = [](int x) { return x % 2 == 0; };
auto evens = v | std::views::filter#include <ranges>(is_even); // 2, 4Views are chained with |, and each step is applied in order:
auto result = v
| std::views::filter#include <ranges>([](int x) { return x % 2 == 1; }) // 1, 3, 5
| std::views::transform#include <ranges>([](int x) { return x * x; }) // 1, 9, 25
| std::views::take#include <ranges>(2); // 1, 9Other common views:
v | std::views::reverse#include <ranges>; // 5, 4, 3, 2, 1
v | std::views::drop#include <ranges>(2); // 3, 4, 5
std::views::iota#include <ranges>(1, 4); // 1, 2, 3Note
Views are lazy-evaluated. Each element is only computed when the view is iterated.
Warning
Using a view after its range has been destroyed is undefined behaviour.
std::ranges::to#include <ranges> collects a view into a new container:
auto squares = v
| std::views::transform#include <ranges>([](int x) { return x * x; })
| std::ranges::to#include <ranges><std::vector#include <vector>>(); // std::vector#include <vector><int> {1, 4, 9, 16, 25}std::views::enumerate#include <ranges> pairs each element with its index, and std::views::zip#include <ranges> pairs up elements from several ranges:
std::vector#include <vector><std::string#include <string>> names = {"Alice", "Bob"};
std::vector#include <vector><int> ages = {30, 25};
for (const auto& [i, name] : std::views::enumerate#include <ranges>(names)) {
std::cout#include <iostream> << i << ": " << name << "\n"; // 0: Alice, 1: Bob
}
for (const auto& [name, age] : std::views::zip#include <ranges>(names, ages)) {
std::cout#include <iostream> << name << " is " << age << "\n"; // Alice is 30, Bob is 25
}
Dan