New usage of for loop in C++11

 C++ iterates over a container as follows:

#include "stdafx.h"
#include<iostream>
#include<vector>

intmain()
{
    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;
}

Among them, auto uses the type deduction of C++11. At the same time, 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;
}

intmain()
{
    std::vector<int> arr;
    arr.push_back(1);
    arr.push_back(2);

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

    return 0;
}

Now C++11's for loop has a new usage:

#include "stdafx.h"
#include<iostream>
#include<vector>

intmain()
{
    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 in arr, you can use for(auto& n:arr). The internal implementation of this method of using the for loop actually relies on iterators, so if you change the If arr is added and deleted, the program will have unexpected errors.

  In fact, this usage has already been implemented in other high-level languages, such as php, Java, and even Qt, which encapsulates C++, and foreach. 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325662800&siteId=291194637