c++11--Range-based for loop

Source: Internet
Author: User

The C++11 has a range-based for loop, and a range-based for loop can no longer care about the concept of iterators, only the element types in the relational container, and the beginning and end of the container without having to be explicitly given.

int arr[] = {1, 2, 3, 4};for (int a:arr) {...} vector<string> str_arr{"Hello", "World", "Fuck"};for (auto V:str_arr) {...} If you want to modify the elements in the container, you can use a reference type: for (auto& V:arr) {...}

When using a range-based for loop, you also need to be aware of some constraints on the container itself. Like what

Because the elements in set and map are stored in a very strong order of size, they cannot be arbitrarily modified by their values std::set<int> s = {1, 2, 3};for (auto& val:s) {    std::cout << Val + + << Endl;    An error occurs because the inner element in the Std::set is read-only, so the auto for the For loop is automatically deduced as a const int&}

Note The for mechanism for a range-based for loop, in which the range-based for loop generally determines the range of iterations before the loop starts, rather than calling Arr.end () one time before each iteration.

Std::vector<int> arr = {1, 2, 3, 4, 5};for (int a:arr) {    ...} Equivalent to auto && __range = (arr); for (Auto __begin = __range.begin (), __end = __range.end (); __begin! = __end; ++__begin) {    ...}

Try not to modify the container of iterations in the iterative process, but when you have to do so, by understanding the characteristics of the range-based for loop, you can easily analyze the results of each iteration and avoid the error of the algorithm in advance.

+

c++11--Range-based for loop

Related Article

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.