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.