Range-Based For
vs. Iterators
Master the two primary ways to traverse containers in modern C++: the elegant range-based for loop and the powerful iterator interface.
What Is a Container?
A container is any C++ object that holds a collection of elements: arrays, vectors, lists, maps, and more. To do anything useful with those elements, you need a way to visit each one in sequence.
The Range-Based For Loop
Introduced in C++11, the range-based for loop gives you the cleanest syntax for visiting every element. You declare a variable and a container: the compiler handles the rest.
std::cout << x << "\n";
}
What Is an Iterator?
An iterator is an object that acts like a pointer: it refers to an element in a container and can be advanced, dereferenced, and compared. Iterators give you precise control over traversal.
Under the Hood
The compiler transforms every range-based for loop into an equivalent iterator loop. Understanding this equivalence is the key insight of this lesson.
process(x);
}
it != vec.end(); ++it) {
auto x = *it;
process(x);
}
Syntax Patterns
Iterator Vocabulary
When to Use Which
| Range-Based For | Iterators | |
|---|---|---|
| Readability | ★★★ Very clean | ★★ More verbose |
| Access to index | ✕ Not built-in | ✓ Via \(\texttt{std::distance}\) |
| Erase during loop | ✕ Unsafe | ✓ Via \(\texttt{it = erase(it)}\) |
| Sub-range traversal | ✕ Always full range | ✓ Any \(\texttt{[first, last)}\) |
| Reverse iteration | ✕ Not directly | ✓ \(\texttt{rbegin() / rend()}\) |
| Best for | Simple reads & writes | Complex mutations |
Decision Flowchart
Step-by-Step Approach
Example 1: Summing Elements
Task: compute the sum of all integers in a vector. This is a simple read-only traversal: range-based for is the clear winner.
int sum = 0;
for (const auto& n : nums) {
sum += n;
}
// sum == 26
Example 2: Doubling in Place
Task: multiply every element by 2. We need to modify each element, so we use a reference.
x *= 2;
}
it != vec.end(); ++it) {
*it *= 2;
}
Example 3: Erasing During Traversal
Task: remove all even numbers from a vector. This requires modifying the container itself during iteration: only iterators can do this safely.
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0) {
it = v.erase(it); // returns next valid iterator
} else {
++it;
}
}
// v == {1, 7, 3}
Example 4: Iterating Maps
Task: print all key-value pairs from a \(\texttt{std::map}\). Both approaches work, but structured bindings (C++17) make range-based for especially clean.
for (const auto& [name, pts] : scores) {
std::cout << name << ": "
<< pts << "\n";
}
it != scores.end(); ++it) {
std::cout << it->first << ": "
<< it->second << "\n";
}
Common Mistakes
Summary Comparison
| Feature | Range-Based For | Iterators |
|---|---|---|
| Syntax | Concise, clean | Verbose, explicit |
| Available since | C++11 | C++98 |
| Traversal direction | Forward only | Forward, reverse, random |
| Sub-range support | ✕ | ✓ Any \(\texttt{[first, last)}\) |
| Erase / insert safe | ✕ | ✓ |
| Works with algorithms | ✕ | ✓ \(\texttt{std::sort}\), \(\texttt{std::find}\), etc. |
| Recommendation | Default choice | When you need control |
Question 1 of 5
Which of the following correctly doubles every element of a \(\texttt{std::vector<int> v}\) using a range-based for loop?
Question 2 of 5
You need to remove all negative numbers from a \(\texttt{std::vector<int>}\). Which approach is safe?
Question 3 of 5
What does the compiler transform \(\texttt{for (auto x : vec)}\) into behind the scenes?
Question 4 of 5
Given \(\texttt{std::map<std::string, int> m}\), which range-based for syntax uses structured bindings to access keys and values?
Question 5 of 5
You want to print only the last 3 elements of a \(\texttt{std::vector<int> v}\) with 10 elements. Which is the best approach?