range-based for loop
In C++11, the range-based for loop was introduced, making it more convenient and intuitive to iterate over elements in a container.
Let’s dive straight into the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>
int main() {
// Create a vector of integers
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Iterate over the elements in the container using a range-based for loop
for (auto x : numbers) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
Execution Result
Usage:
- When you need to iterate over all elements in a container (such as a vector, list, map, etc.), the range-based for loop provides a concise and easy-to-understand syntax.
- When you don’t need the index value or iterator, and only need to access the elements in the container, the range-based for loop is more convenient.
Same functionality, but much more readable! It’s just that simple!

