New Features of C ++ 11 (6) range-based for Loop

Source: Internet
Author: User

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.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.