Lesson 44 of 45
C++Lesson 44: Ranges Library (C++20)
14 min
Course progress98%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 44 of 45
C++14 min
Keep these ideas in mind as you work through the lesson.
The Ranges library unifies algorithms and containers under a common view‑based approach. Views are lazy, composable adapters that transform a range without materialising intermediate containers.
std::views::filterstd::views::transformstd::views::takestd::views::dropstd::views::reversestd::vector<int> numbers = {1, 2, 3, 4, 5, 6};
auto evenSquares = numbers
| std::views::filter([](int n){ return n % 2 == 0; })
| std::views::transform([](int n){ return n * n; });
for (int v : evenSquares) {
std::cout << v << ' ';
}
std::cout << '\
';
The above pipeline never creates a temporary container; each element is processed on‑the‑fly.
std::ranges::sortstd::vector<std::string> words = {\"apple\", \"banana\", \"cherry\"};
std::ranges::sort(words, std::greater{}); // sort descending
for (const auto& w : words) std::cout << w << ' ';
std::cout << '\
';
Tip: When an algorithm accepts a range (e.g.,
std::ranges::find), you can pass a view directly without calling.begin()/.end().
<Alert type="warning">Views hold references to the underlying container; ensure the container outlives the view to avoid dangling references.