Range-based for Loop in C++
Learn the range-based for loop in C++ to iterate through arrays and STL containers with cleaner and more readable code.
Introduced in C++11, the range-based for loop provides a modern, clean, readable, and safe way to iterate over arrays and collections. It reduces the complexity of traditional for loops and works seamlessly with all STL containers.
In this article, we explain the syntax, advantages, and various practical examples of the range-based for loop.
1) Basic Syntax
The structure is quite simple:
for (auto element : collection) {
// operation
}
This assigns each element of the collection to the variable in sequence.
2) Using with Arrays
int numbers[] = {1, 2, 3, 4, 5};
for (auto n : numbers) {
cout << n << endl;
}
3) Using References (&)
If you want to modify elements inside the loop, you must use a reference:
vector<int> values = {1, 2, 3};
for (auto& v : values) {
v *= 10;
}
After the loop, values → {10, 20, 30}
4) Using const References
For large objects, copying is expensive. Using const & prevents copying and ensures read-only access:
vector<string> names = {"John", "Emily", "Michael"};
for (const auto& name : names) {
cout << name << endl;
}
5) Using with STL Containers
All STL containers fully support range-based for:
vector<double> values = {1.1, 2.2, 3.3};
list<string> cities = {"London", "Paris", "Berlin"};
set<int> ages = {25, 30, 35};
for (auto v : values) cout << v << endl;
for (auto& c : cities) cout << c << endl;
for (auto a : ages) cout << a << endl;
6) Using with map
A map stores key-value pairs, so the syntax is slightly different:
map<string, int> grades = {
{"John", 85},
{"Emily", 92},
{"Michael", 78}
};
for (auto& [name, score] : grades) {
cout << name << " : " << score << endl;
}
C++17 structured bindings make this extremely clean and easy.
7) Using break and continue
vector<int> nums = {1, 2, 3, 4, 5};
for (auto n : nums) {
if (n == 3)
continue;
if (n == 5)
break;
cout << n << endl;
}
8) Advantages of the Range-based for Loop
- Much cleaner and more readable
- Eliminates the need for manual iterators
- Reduces chances of off-by-one errors
- Works with all STL containers and arrays
- Great with C++17 structured bindings
9) Disadvantages
- Not ideal when index-based operations are required
- Iterators provide more control for special cases
- For maps and unordered_maps, structured bindings are recommended
10) TL;DR
- Range-based for is simple, clean, and safe
- Combines perfectly with auto, references, and const references
- Introduced in C++11, improved with C++17 structured bindings
- In modern C++, it should be preferred over traditional loops whenever possible