How to Use Ranges in C++: Syntax and Examples
In C++, ranges are used to work with sequences of elements more easily using the
std::ranges library introduced in C++20. You can use range-based for loops, views, and algorithms that accept ranges to write cleaner and more expressive code.Syntax
The basic syntax for using ranges involves range-based for loops and the std::ranges library functions. A range is any object that has a beginning and an end, like containers or views.
for (auto& element : range) { ... }— iterates over elements in the range.std::ranges::views— creates lazy views over ranges.std::ranges::algorithm— algorithms that accept ranges directly.
cpp
for (auto& element : range) { // use element } // Using ranges algorithms #include <ranges> #include <vector> std::vector<int> v = {1, 2, 3, 4, 5}; auto filtered = v | std::ranges::views::filter([](int n) { return n % 2 == 0; });
Example
This example shows how to use a range-based for loop and std::ranges::views::filter to iterate over even numbers in a vector.
cpp
#include <iostream> #include <vector> #include <ranges> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6}; // Create a view that filters even numbers auto even_numbers = numbers | std::ranges::views::filter([](int n) { return n % 2 == 0; }); std::cout << "Even numbers:"; for (int n : even_numbers) { std::cout << ' ' << n; } std::cout << '\n'; return 0; }
Output
Even numbers: 2 4 6
Common Pitfalls
Common mistakes when using ranges include:
- Not including the
<ranges>header. - Trying to use ranges features in C++ versions before C++20.
- Forgetting that views are lazy and do not store data themselves.
- Using range-based for loops on objects that are not ranges.
cpp
#include <iostream> #include <vector> // Missing <ranges> header int main() { std::vector<int> v = {1, 2, 3}; // This will cause a compile error because views are not available // auto filtered = v | std::ranges::views::filter([](int n) { return n > 1; }); // Correct way: include <ranges> and compile with C++20 return 0; }
Quick Reference
Range-based for loop: for (auto& x : range) { ... }
Filter view: auto filtered = range | std::ranges::views::filter(predicate);
Transform view: auto transformed = range | std::ranges::views::transform(func);
Common algorithms: std::ranges::sort(range); std::ranges::find(range, value);
Key Takeaways
Ranges in C++20 simplify working with sequences using views and range-based for loops.
Always include and compile with C++20 or later to use ranges features.
Views are lazy and do not copy data; they create a transformed view of the original range.
Use std::ranges algorithms directly on ranges for cleaner and safer code.
Common views include filter, transform, and take, which help process data efficiently.