New usage of C ++ 11 for loop, 11for Loop

Source: Internet
Author: User

New usage of C ++ 11 for loop, 11for Loop

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;}

Auto uses the C ++ 11 type derivation. At the same time, we can use std: for_each to complete 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 preceding method is read-only. If you need to modify the values in arr, you can use for (auto & n: arr). The internal implementation of the for loop is actually implemented using the iterator, therefore, if you add or delete arr during the loop process, the program will encounter unexpected errors.

In fact, this usage has been implemented in other advanced languages, such as php, Java, and even Qt encapsulated for C ++. foreach is also available.

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.