C++11 new Features (6) range-based for loop

Source: Internet
Author: User



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.











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.