Monday, March 12, 2012

C++'11: Ranged for loops

First for orientation, consider the current for loop
for(int i = 0; i < 10; i++)
array[i] = 0;
The standard states that
for ( for-init-statement condition; expression) statement 
is equivenent to
{
for-init-statement
while ( condition {
statement
expression ;
}
}
No big surprises there, just reordering where the pieces fit. Now consider the new ranged based for loop which is defined similarly as
for ( for-range-declaration : expression ) statement 
is equivalent to
{
auto && __range = (expression);
for ( auto __begin = begin-expr, __end = end-expr;
__begin != __end;
++__begin)
{
for-range-declaration = *__begin;
statement
}
Not quite so straight forward, but not to worry because it probably behaves the way you would expect it to. The __ variables were defined only to help explain the syntax, they don't really exist. The begin-expr and end-expr are dependent on the type that expression evaluates to. If expression is an array, then they are the beginning and one past the ending of the array respectively. If the length of the array is not known then it is invalid and should not compile. If expression is a class, then it is __range.begin() and __range.end(). If there are not member functions by that name, then argument dependent lookup (ADL) is used to find the functions that would be valid for begin(__range) and end(__range)

Here is an array example:
int array[6] = {2,3,5,7,11,13};
for( const auto prime : array) cout << prime << endl;
Here is a class example:
void printIncrement( vector& vect )
{
for(auto x : vect) cout << x << endl;
for(auto &x : vect) ++x; //need reference to make the ++ save in the original vector
}

No comments:

Post a Comment