Vector loop
- C++ course
- Beginner
- Lesson 63/116
- 5 min
Learn to iterate over a vector with range-based for.
Looping with range-based for
The range-based for loop is a short way to walk through every element of a vector in order. Its form is for (int x : nums) { std::cout << x; }. Here x takes one element of the vector each turn; you do not handle an index.
This form is ideal when you only read or print elements. When no index is needed, range-based for is preferred over the classic for; it is less error-prone. Modifying the element requires a reference, which we cover in a later level.
Modifying inside the loop
In a range-based for you get a copy of the element; changes to x do not affect the vector. for (int x : nums) { x = 0; } only zeros the local copy, not nums.
To change the vector itself you need a reference, which you will see in the references topic. For now use range-based for only for reading and printing; when you need to modify elements, you will need a classic for or a reference.
Practice Print with range-based for
Declare std::vector<int> nums = {2, 4, 6, 8};. Print every element on a single line, adjacent to each other, using a range-based for.
Starter code
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {2, 4, 6, 8};
// Print with a range-based for
return 0;
}Sample solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {2, 4, 6, 8};
for (int x : nums) {
std::cout << x;
}
std::cout << std::endl;
return 0;
}Expected output
2468
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the loop forms
| Term | Meaning |
|---|---|
for (int x : nums) |
Range-based for |
for (int i = 0; ...) |
Classic for |
nums.size() |
Loop bound |
std::cout << x |
Print the element |
2 What does for (int x : nums) { std::cout << x; } print? (nums = {1, 2, 3})
std::vector<int> nums = {1, 2, 3};
for (int x : nums) { std::cout << x; }- 1 2 3
- 3 2 1
- 6
- 123 Correct answer
Explanation: each element is printed without separator: 123.
3 Complete the range-based for
for (int x ____ nums) { std::cout << x; }
for (int x : nums) { std::cout << x; }
Explanation: the : separator walks the vector.