Solemnly declare: This article is written by the author based on my personal understanding. errors are inevitable. Please be prepared!
You can reprint, modify, and indicate the source when reprinting!
Range-for is a new feature of C ++ 11. It is used to iterate a "range" in a loop. This "range" is similar to an STL sequence container containing the begin () and end () methods. All STL standard containers apply to this range, such as vector and string. The array can also be used. As long as any "range" of the begin () and end () methods are defined, you can use "for" to iterate elements in the container, such as istream.
Syntax:
for ( range_declaration : range_expression) loop_statement
The effects of the above Code are similar:
(__range, __begin and __end are for exposition only):
{ auto && __range = range_expression ; for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) { range_declaration = *__begin; loop_statement } }
Range_expressionUsed to determine the sequence or range to be iterated. Each element in the sequence is dereferenced and assignedRange_declarationThe specified variable.
The iterator begin_expr and end_expr can be defined as the following types:
* If_ RangeIs an array,(_ Range) And (_ Range + _ bound) Indicates the range of the array.
* If_ RangeIs a class that implements the begin () or end () methods, or both methods.begin_exprIndicates_ Range. Begin (), while End_expr indicates __range.end()。
Otherwise, begin (_ Range) And end (_ RangeBased on the parameter dependency Search rules associated with the STD namespace.
IfRange_expressionReturns a temporary variable whose lifecycle ends with the end of the loop, such as binding to the right value.__range, But note that temporary nesting inRange_expressionDoes not extend its lifecycle.
Like a traditional for statement, the keyword break can end the loop in advance, while the continue can continue the loop.
Example:
1 void F (vector <double> & V) 2 {3 for (Auto X: V) cout <x <'\ n'; 4 for (Auto & X: v) ++ X; // you can modify the value 5 in V through reference}
For can also be used to iterate common arrays, such:
for (const auto x : { 1,2,3,5,8,13,21,34 }) cout << x << '\n';
Misunderstanding 1:
1 int* p = new int [2];2 p[0] = 1;3 p[1] = 2;4 for (auto x : p) cout << x << endl;
The compiler reports an error:
Error: no matching function exists for 'in in (int * &) 'calls.
Through the introduction of for, we can know that the for implementation mechanism is dependent on the begin () and end () methods in the container. For common arrays, the compiler has implemented similar methods by default. P here is a pointer. Although it can be used like an array, it does not have a method similar to begin () or end (). Of course it will not be compiled.
References:
Http://www.stroustrup.com/C++11FAQ.html
Http://en.cppreference.com/w/cpp/language/range-for