New Features of C ++ 11 (6) range-based for Loop
In C ++ 11, a Range-based for loop is added, which saves much of our code.
From Wikipedia: http://zh.wikipedia.org/wiki/C++0x#.E5.80.99.E9.81.B8.E8. AE .8A.E6.9B.B4
Boost C ++ defines many concepts of "range. The range is like a list, which holds two points in the container. An ordered container is a superset of the range concept. Two iterators in an ordered container can also define a range. These concepts and operating algorithms will be incorporated into the C ++ 11 standard library. However, C ++ 11 will provide the scope concept utility at the language level.
ForThe statement will allow simple range iteration:
int my_array[5] = {1, 2, 3, 4, 5};for (int &x : my_array){ x *= 2;}
AboveForThe first definition of the sentence is used for range iteration parameters. Just like the parameters declared in a general for loop, its scope is only within the loop range. The second block after ":" represents the scope of iteration. In this way, a conceptual diagram that allows the C-style array to be converted into a range concept is created. This can beStd: vectorOr other objects that conform to the scope concept.
Application of range-based for loop in common Arrays:
# Include
Using namespace std; int main () {int arr [10] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int I: arr) {cout <
Running result:
In STL containers, the time duration is more convenient.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink">
VcD4KPHA + CjxwcmUgY2xhc3M9 "brush: java;"> # include
# Include
Using namespace std; int main () {vector
Arr {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int & I: arr) {cout <
Result:
With this, it is very convenient to traverse the elements in the range.