Range-based for
- C++ course
- Intermediate
- Lesson 62/116
- 5 min
Learn the relation between range-based for and iterators.
Range-based for
The range-based for loop is a short form of the iterator-based loop: for (auto x : v) { ... }. The compiler calls v.begin() and v.end() behind the scenes and assigns each element to the loop variable in turn.
So for (auto x : v) is equivalent to for (auto it = v.begin(); it != v.end(); ++it) { auto x = *it; ... }. That is why range-based for works on any container that supports iterators. You make fewer typing mistakes and the code reads more naturally.
Reference and copy
In range-based for, auto x is a copy of the element; changes to x do not affect v and large elements cost performance. auto& x takes a reference; modifying x modifies the element in v and there is no copy cost.
For read-only loops use const auto& x. It avoids the copy cost and prevents accidental modification. These three forms are very common in modern C++: auto, auto&, const auto&.
Practice Double elements with range-based for
For v = {1, 2, 3}, double each element with for (auto& x : v). Then in a separate for (int x : v) print each element followed by a space.
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
// Double each element with range-based for, then print
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
for (auto& x : v) {
x = x * 2;
}
for (int x : v) {
std::cout << x << " ";
}
return 0;
}Expected output
2 4 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does for (auto x : v) do?
std::vector<int> v = {1, 2, 3};
for (auto x : v) { }- Creates an infinite loop
- Creates a copy of v
- Permanently modifies v
- Copies each element into x and iterates Correct answer
Explanation: Each element is copied into x in turn.
2 Complete the range-based for syntax
for (auto ____ : v) {
std::cout << x;
}
for (auto x : v) {
std::cout << x;
}
Explanation: for (auto x : v) creates a by-value loop.
3 Match each form to its purpose
| Term | Meaning |
|---|---|
for (auto x : v) |
Copy loop |
for (auto& x : v) |
Reference loop |
for (const auto& x : v) |
Read-only |
v.begin(), v.end() |
Called behind the scenes |