01 / 21

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.

C++

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.

10 20 30 40 50 ...
\(\texttt{std::vector<int>}\)

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.

for (auto x : vec) {
    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.

10 20 30 40 50 it begin() end() ∅

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.

Range-Based For
for (auto x : vec) {
  process(x);
}
Equivalent Iterator Loop
for (auto it = vec.begin();
     it != vec.end(); ++it) {
  auto x = *it;
  process(x);
}

Syntax Patterns

By Value
\(\texttt{for (auto x : vec)}\)
Copies each element. Safe, but cannot modify the original.
By Reference
\(\texttt{for (auto\& x : vec)}\)
Refers to the original element. Allows modification in place.
By Const Ref
\(\texttt{for (const auto\& x : vec)}\)
Read-only access. No copies, no modifications: the gold standard for reading.

Iterator Vocabulary

1
\(\texttt{begin()}\) / \(\texttt{end()}\): return iterators to the first element and one-past-the-last.
2
\(\texttt{*it}\) (dereference): access the element the iterator points to.
3
\(\texttt{++it}\) (increment): advance to the next element.
4
\(\texttt{it != end()}\) (compare): check if there are more elements.
5
\(\texttt{cbegin()}\) / \(\texttt{cend()}\): const iterators that prevent modification.

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

Need to traverse? Erase or insert during loop? Yes Use Iterators No Partial / reverse traversal? Yes Use Iterators No Need element index? Yes Index loop or Iterators No Range-Based For ✓

Step-by-Step Approach

1
Identify the container. Is it a vector, list, map, set, or array?
2
Determine your goal. Read-only? Modify in place? Erase elements? Traverse a sub-range?
3
Choose your tool. Simple full traversal → range-based for. Complex mutation → iterators.
4
Pick the right qualifier. Use \(\texttt{const auto\&}\) for reading, \(\texttt{auto\&}\) for writing, \(\texttt{auto}\) for cheap copies.
5
Test edge cases. Empty containers, single elements, and large collections should all work.

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.

std::vector<int> nums = {3, 7, 2, 9, 5};
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.

Range-Based (auto&)
for (auto& x : vec) {
  x *= 2;
}
Iterator Version
for (auto it = vec.begin();
     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.

std::vector<int> v = {1, 4, 7, 2, 8, 3};

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.

Range-Based + Bindings
std::map<std::string, int> scores;

for (const auto& [name, pts] : scores) {
  std::cout << name << ": "
           << pts << "\n";
}
Iterator Version
for (auto it = scores.begin();
     it != scores.end(); ++it) {
  std::cout << it->first << ": "
           << it->second << "\n";
}

Common Mistakes

✕ Erasing in Range-For
Calling \(\texttt{erase()}\) inside a range-based for loop invalidates the hidden iterator, causing undefined behavior.
✕ Forgetting the Reference
Writing \(\texttt{auto x}\) instead of \(\texttt{auto\& x}\) creates a copy: modifications don't affect the original container.
✕ Double Increment
In an erase loop, writing \(\texttt{++it}\) in both the if-branch and the for-header skips elements after erasing.

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?