C++ for each loop (new in C11)
The C++11 standard introduced a new type of loop called the range-based for loop, or the "for each" loop. This loop allows you to iterate over the elements of a container (such as an array, vector, or list) without having to manage an index variable or pointer.
Here's the syntax of a range-based for loop:
for (type var : container) { // Code to execute for each element in the container }
In this syntax, type
is the data type of the elements in the container, var
is a variable that will hold each element of the container in turn, and container
is the container you want to iterate over.
Here's an example of using a range-based for loop to iterate over the elements of a vector:
#include <vector> #include <iostream> int main() { std::vector<int> numbers = { 1, 2, 3, 4, 5 }; for (int n : numbers) { std::cout << n << std::endl; } return 0; }
In this example, the range-based for loop iterates over each element in the numbers
vector, and assigns the value of each element to the variable n
. The code inside the loop then prints the value of n
to the console.
The output of this code will be:
1 2 3 4 5
The range-based for loop is a convenient and easy-to-read way to iterate over the elements of a container. It can simplify your code and make it more expressive.