The C++11 has a range-based for loop, and a range-based for loop can no longer care about the concept of iterators, only the element types in the relational container, and the beginning and end of the container without having to be explicitly given.
int arr[] = {1, 2, 3, 4};for (int a:arr) {...} vector<string> str_arr{"Hello", "World", "Fuck"};for (auto V:str_arr) {...} If you want to modify the elements in the container, you can use a reference type: for (auto& V:arr) {...}
When using a range-based for loop, you also need to be aware of some constraints on the container itself. Like what
Because the elements in set and map are stored in a very strong order of size, they cannot be arbitrarily modified by their values std::set<int> s = {1, 2, 3};for (auto& val:s) { std::cout << Val + + << Endl; An error occurs because the inner element in the Std::set is read-only, so the auto for the For loop is automatically deduced as a const int&}
Note The for mechanism for a range-based for loop, in which the range-based for loop generally determines the range of iterations before the loop starts, rather than calling Arr.end () one time before each iteration.
Std::vector<int> arr = {1, 2, 3, 4, 5};for (int a:arr) { ...} Equivalent to auto && __range = (arr); for (Auto __begin = __range.begin (), __end = __range.end (); __begin! = __end; ++__begin) { ...}
Try not to modify the container of iterations in the iterative process, but when you have to do so, by understanding the characteristics of the range-based for loop, you can easily analyze the results of each iteration and avoid the error of the algorithm in advance.
+
c++11--Range-based for loop