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"