What is the purpose of foreach in C++?

In C++, the foreach statement is used to traverse elements in a container, simplifying the process of iterating through the container. Using foreach can avoid manually managing iterators or indexes, making the code more concise and readable.

The syntax of the foreach statement is as follows:

for (element_decl : container) {
    // 循环体
}

In each iteration of the loop, the variable element_decl is declared to receive the value of each element in the container to be traversed, which can be an array, vector, list, or other container type. By using foreach, we can conveniently loop through each element in the container without needing to manually use iterators or indexes to access them.

bannerAds