01 / 21

Range-Based
For Loops

Master the modern C++ way to iterate over containers with clean, expressive, and less error-prone syntax.

C++

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?

✓ Readability
Clearly expresses intent: "for each element, do this." No index clutter.
✓ Safety
Eliminates off-by-one errors and out-of-bounds access entirely.
✓ Brevity
Fewer lines of code. Less boilerplate means fewer places for bugs to hide.

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:

Standard Library
vector, array, list, deque, set, map, string
Built-in Arrays
C-style arrays like int arr[5] with known size at compile time
Initializer Lists
Inline braces: {1, 2, 3} directly in the loop

The Syntax

for ( declaration : expression ) { ... } Loop variable Type + name for each element Range Container or iterable object

Under the Hood

The compiler transforms your range-based for loop into an equivalent iterator-based loop. Here's what actually happens:

YOU WRITE for ( auto x : vec ) cout << x ; BECOMES COMPILER GENERATES { auto __b = vec. begin (); auto __e = vec. end (); for (; __b != __e; ++__b) { auto x = *__b; cout << x; } } Key insight: The range expression is evaluated exactly once. The iterators __b and __e are cached at the start. Warning: Modifying the container's size during iteration invalidates the cached end iterator: undefined behavior!

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

1
Identify the container. Confirm it supports begin()/end() (STL containers, arrays, or custom types).
2
Choose the access mode. Read-only? Use const auto&. Need to modify? Use auto&. Small primitive copy? Use auto.
3
Write the loop. for (const auto& elem : container) { ... }
4
Use the element directly. No need for container[i] or *it: the variable already holds each element.
5
Do NOT resize the container inside the loop body: no push_back, erase, or insert.

Example 1: Iterating a Vector

C++ : Summing elements
vector<int> scores = {85, 92, 78, 96, 88}; int total = 0; for (const auto& s : scores) { total += s; } // total == 439

Example 2: Modifying Elements

C++ : Doubling each value
vector<int> nums = {1, 2, 3, 4, 5}; for (auto& n : nums) { n *= 2; // modifies original } // nums is now {2, 4, 6, 8, 10}

Example 3: Iterating a Map

C++ : Structured bindings (C++17)
map<string, int> ages = { {"Alice", 17}, {"Bob", 16}, {"Carol", 18} }; for (const auto& [name, age] : ages) { cout << name << ": " << age << "\n"; }

Example 4: Iterating a String

C++ : Counting vowels
string word = "Algorithm"; int vowels = 0; for (const auto& ch : word) { if (string("aeiouAEIOU").find(ch) != string::npos) vowels++; } // vowels == 3 (A, o, i)

Initializer Lists & C-Style Arrays

C++ : Inline initializer list
// Inline braced list (no named container) for (auto x : {10, 20, 30}) { cout << x << " "; } // Output: 10 20 30 // C-style array int arr[] = {5, 10, 15}; for (auto val : arr) { cout << val << " "; }

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:

auto
Compiler deduces the type. Flexible, less typing, adapts if container type changes.
Explicit type
You write the type yourself, e.g. int or string. More readable for beginners, but brittle.

Common Mistakes

✕ Modifying container size
Calling push_back(), erase(), or insert() during iteration invalidates iterators: undefined behavior.
✕ Forgetting the reference
Using auto x instead of auto& x creates a copy. Your modifications won't affect the original container.
✕ Using with pointer arrays
Passing a C-array to a function decays it to a pointer. Range-based for loops can't iterate pointers: they need a known size.

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)?