Modern C++ • C++20 baseline
Ranges and Views in C++20
Compose lazy transformations and filters while respecting the lifetime of the underlying range.
C++20 ranges provide constrained range algorithms and composable views. A view can defer work until iteration and may refer to another object rather than own its elements. Keep the underlying range alive for as long as the view is used, and materialize results when ownership or repeated traversal requires it.
Key points
- Views can be lazy and non-owning.
- A range pipeline does not automatically make an expensive operation constant-time.
Example
#include <iostream>
#include <ranges>
#include <vector>
int main() {
const std::vector<int> values{1, 2, 3, 4, 5, 6};
auto selected = values
| std::views::filter([](int value) { return value % 2 == 0; })
| std::views::transform([](int value) { return value * value; });
for (int value : selected) {
std::cout << value << ' ';
}
}
What to expect
4 16 36
Practice exercise
Add a filter for values greater than two and explain which transformations are evaluated during iteration.
Key idea: Ranges make pipelines expressive, but view ownership and evaluation behavior still matter.