The c++11 contains a new for loop, called a range-based for loop, that simplifies the traversal of array elements. The format is as follows:
1 for (Type varname:array) {2 // the value of each element is assigned to VarName in turn 3 }
For example:
1 int array[] = {1234}; 2 for (int x:array) {3 cout << x; 4 }5 cout << Endl;
Example will output: 1234
When defining variables for traversing an array, you can use the same modifiers as normal function parameters. The x variable in this example is equivalent to the value of the pass parameter. Changing the x inside the loop does not change the array. But if you use & to define X as a reference, the changes to X are reflected in the array. You can use the const modifier to specify that a variable cannot be modified.
The following example adds each element of an array to the output. The output loop automatically determines the type of the array element with the auto data type.
1 int array[] = {2 , 4 , 6 , 8 2 int &x:array) { 3 X++; 4 5 for 6 cout << X; 7 8 cout << Endl;
Output Result: 3579
C++11 Range-based for loop