Range-Based
For Loops
Master the modern C++ way to iterate over containers with clean, expressive, and less error-prone syntax.
What is a Range-Based For Loop?
A range-based for loop (introduced in C++11) lets you iterate over every element in a container or range without manually managing an index or iterator. It's the modern, preferred way to traverse collections in C++.
Why Use Range-Based Loops?
What Containers Can You Iterate?
A range-based for loop works with any type that provides begin() and end() iterators. This includes all Standard Library containers and more:
The Syntax
Under the Hood
The compiler transforms your range-based for loop into an equivalent iterator-based loop. Here's what actually happens:
By Value vs By Reference vs Const Ref
| auto x | auto& x | const auto& x | |
|---|---|---|---|
| Creates a | Copy | Reference | Const reference |
| Modify original? | No | Yes | No |
| Copy cost? | Copies each element | No copy | No copy |
| Best for | Small types (int, char) | Mutation needed | Read-only, large types |
How to Apply It
Example 1: Iterating a Vector
Example 2: Modifying Elements
Example 3: Iterating a Map
Example 4: Iterating a String
Initializer Lists & C-Style Arrays
The Power of auto
The auto keyword tells the compiler to deduce the element type automatically. You can also be explicit, but auto is usually preferred:
Common Mistakes
Traditional vs Range-Based
| Index-Based | Iterator-Based | Range-Based | |
|---|---|---|---|
| Boilerplate | High | High | Low |
| Off-by-one risk | Yes | Possible | None |
| Access to index | Yes | Via distance() | No (need workaround) |
| Reverse iteration | Easy | rbegin/rend | Needs adapter |
| Works with all containers | Random access only | Yes | Yes |
Question 1 of 5
What is the correct syntax for a range-based for loop that reads each element of a vector<string> names without copying?
Question 2 of 5
You want to double every element in a vector<int>. Which loop variable declaration should you use?
Question 3 of 5
What happens if you call vec.push_back(42) inside a range-based for loop that is iterating over vec?
Question 4 of 5
Which of the following cannot be used with a range-based for loop?
Question 5 of 5
In C++17, what feature allows you to write for (const auto& [key, val] : myMap)?