A range-based for loop has been added to C++11, which saves us a lot of code.
Explanation from Wikipedia: http://zh.wikipedia.org/wiki/C++0x#.E5.80.99.E9.81.B8.E8.AE.8A.E6.9B.B4
Boost C + + defines a number of "range" concepts. The range behaves like a controlled list, holding two points in the container. An ordered container is a superset of the scope concept (superset), and the two iterators (iterator) in an ordered container can also define a range. These concepts, as well as the operational algorithms, will be incorporated into the C++11 standard library. However, the c++11 will be supported by the language level to provide the usefulness of the scope concept.
The For statement will allow a simple range iteration:
int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array)
{
x *= 2;
}
Thefirst part of the definition for the sentence above is used to make the parameters of the range iteration, just like the parameters declared in the general for loop, whose scope is only the scope of the loop. The second block after the ":" represents the range that will be iterated. In this way, there is a concept map that allows the C-style array to be transformed into a range concept. This can bestd::vector, or other objects that conform to the scope concept.
Application of a range-based for loop in a normal array:
#include <iostream>
using namespace std;
int main()
{
int arr[10]{1,2,3,4,5,6,7,8,9,10};
for(int i:arr){
cout<<i<<" ";
}
cout<<endl;
}
Operation Result:
It is more convenient to traverse in the STL container.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr{1,2,3,4,5,6,7,8,9,10};
for(int &i:arr){
cout<<i<<" ";
}
cout<<endl;
Results:
With this, it is very convenient to traverse the elements within the range.