Loading lessons...
Range-Based For Loop (For-Each)
Range-Based For Loop (For-Each)
The range-based for loop visits every element of a collection without counting indexes. C++ does the bookkeeping for you.
The shape
for (type item : collection) {
// use item
}
typeis the type of one element.itemis a new variable that holds each element in turn.collectionis the thing to walk through.- The loop runs the body once per element.
A vector example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {10, 20, 30};
for (int num : nums) {
cout << num << endl;
}
return 0;
}
The loop prints 10, 20, 30. No indexes, no i < size, no off-by-one mistakes.
It works on arrays and strings too
The same loop handles plain arrays and std::string:
int scores[] = {90, 80, 70};
for (int s : scores) {
cout << s << " ";
}
string word = "hey";
for (char c : word) {
cout << c << " ";
}
For a string, each element is a single character.
TL;DR
for (type item : collection)visits each element in order.- No index or size is needed; C++ handles the range.
- It works with arrays, vectors, and strings.
- In a string, each item is one character.