So according to n2243 the range-based for loop is equivalent to this:
{
auto && __range = ( expression );
for ( auto __begin = std::Range<_RangeT>::begin(__range),
__end = std::Range<_RangeT>::end(__range);
__begin != __end;
++__begin )
{
for-range-declaration = *__begin;
statement
}
}
It then says 2 If the header <iterator_concept> is not included prior to a use of the range-based for statement, the program is ill-formed.
so I question how up to date this is. I'm also curious what std::Range
is or if it's purely an implementation detail. The closest I can find is n3350.
This answer relies on this information and says:
Range for is as fast as possible since it caches the end iterator[citation], uses pre-increment and only dereferences the iterator once.
so if you tend to write:
for(iterator i = cont.begin(); i != cont.end(); i++) { /**/ }
Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).
P.S. I said it's as fast as possible, it isn't however faster than possible. You can achieve the exact same performance if you write your manual loops carefully.
I'm curious if it actually makes a difference now. As far as I can see it's just syntactic sugar. For example, in a loop where you could do auto it = s.rbegin(); it != s.rend(); ++it
, it would require boiler plate code that returns reverse iterators where the ranged-based for loop expects begin
and end
. And if all it saves is typing, then what other advantages does it offer, since it only expects begin
and end
? I'm curious if the answer I quoted above still holds weight since the paper is from 2007.