C++11 Range-based for loop

Source: Internet
Author: User

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

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.