What is the usage of foreach in C++?
In C++, the foreach loop is commonly referred to as the range-based for loop or simply the for each loop. It is a new syntax structure introduced in the C++11 standard for conveniently iterating through elements of containers or other iterable objects.
The syntax format for a foreach loop is as follows:
for (element : collection) {
// 执行循环体操作
}
In this case, ‘element’ is the variable used to store each iterated element, and ‘collection’ is the container or iterable object that needs to be traversed.
When using a foreach loop, the compiler will automatically infer the type of the element, and the value of the element will be automatically assigned to each element in the collection during each loop iteration.
Here is an example of iterating through a vector container using a foreach loop.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
The output is: 1 2 3 4 5.
The foreach loop allows for a more concise and intuitive way to iterate through containers. It can be used with all containers that support iterators, such as vector, list, set, as well as other iterable objects like arrays and strings.