Range-based for
- C++ course
- Beginner
- Lesson 45/116
- 5 min
Learn to iterate over collections with range-based for.
Range-based for
To walk every element of a vector or array in order you use a range-based for loop. Its form is for (int x : nums) { ... }; on each iteration x takes the next element of the collection.
You write no initialization, condition or increment; C++ handles them automatically. It is preferred over the classic for when no index is needed because it reads better. Making the loop variable const int& also avoids unnecessary copies.
The advantage of range-based for
The biggest advantage of range-based for is that it removes index errors. With nums[i] you might give i in the wrong range; with range-based for each element comes automatically.
This construct fits only when you walk the collection from start to end. When you need an index, want to skip elements or modify the collection, the classic for is more suitable. Using each tool in the right place makes your code more robust.
Practice Print vector elements
The nums vector is set to {1, 2, 3}. Use for (int x : nums) to print each element with std::cout << x; on a single line. The output must be 123.
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
// Print with range-based for
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
for (int x : nums) {
std::cout << x;
}
std::cout << std::endl;
return 0;
}Expected output
123
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a range-based for loop?
// collection loop- for (i = 0; i < n; i++)
- for (int x : nums) Correct answer
- for (x in nums)
- for (int x; nums)
Explanation: for (int x : nums) is the range-based for form.
2 Write the range-based for body
std::vector<int> nums = {1, 2, 3};
for (int x : nums) {
std::cout << ____;
}
std::vector<int> nums = {1, 2, 3};
for (int x : nums) {
std::cout << x;
}
Explanation: x is the loop variable and holds each element in turn.
3 Match each range-based for part to its role
| Term | Meaning |
|---|---|
int x |
Loop variable |
nums |
Collection |
: |
Means 'in' |
{ ... } |
Body |