New usage of c++11 for loop "Turn"

Source: Internet
Author: User


Related information: New usage of https://legacy.gitbook.com/book/changkun/cpp1x-tutorial/detailsC++11 for loops


C + + uses the following method to traverse a container:


#include "stdafx.h" #include<iostream> #include<vector> int main()
{
    std::vector<int> arr;
    arr.push_back(1);
    arr.push_back(2); for (auto it = arr.begin(); it != arr.end(); it++)
    {
        std::cout << *it << std::endl;
    } return 0;
}


Where auto uses the type derivation of the c++11. We can also use Std::for_each to accomplish the same function:


#include "stdafx.h" #include<algorithm> #include<iostream> #include<vector> void func(int n)
{
    std::cout << n << std::endl;
} int main()
{
    std::vector<int> arr;
    arr.push_back(1);
    arr.push_back(2);

    std::for_each(arr.begin(), arr.end(), func); return 0;
}


Now the c++11 for Loop has a new usage:


#include "stdafx.h" #include<iostream> #include<vector> int main()
{
    std::vector<int> arr;
    arr.push_back(1);
    arr.push_back(2); for (auto n : arr)
    {
        std::cout << n << std::endl;
    } return 0;
}


The above method is read-only, if you need to modify the value inside arr, you can use the for (auto& N:arr), the inner implementation of this usage of the For loop is actually an iterator, so if you increment and delete arr during the loop, Then the program will have unexpected errors.



In fact, this usage has been implemented in other high-level languages, such as Php,java, or even the encapsulation of C + + Qt,foreach.



Original address: http://www.cnblogs.com/jiayayao/p/6138974.html



New usage of c++11 for loop "Turn"


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.