In C++ I need to iterate a certain number of times, but I don\'t need an iteration variable. For example:
for( int x=0; x<10; ++x ) {
/* code goes her
There isn't any way to make a range based for work for simply iterating over several numbers.
C++11 range-based loops require a ranged expression which may be:
begin()
and end()
orbegin()
and end()
(via ADL)In addition to that: A range based for produces some overhead:
for ( for_range_declaration : expression ) statement
expands to
range_init = (expression)
{
auto && __range = range_init;
for ( auto __begin = begin_expr,
__end = end_expr;
__begin != __end;
++__begin ) {
for_range_declaration = *__begin;
statement;
}
}
Where begin_expr and end_expr are obtained via array inspection or begin()
/ end()
pairs.
I don't think this gets any "cleaner" than a simple for-loop. Especially with respect to performance. No calls, just a plain loop.
The only way I can figure out to make it more elegant (where elegant is clearly subject to my opinion) is by using a size or unsigned type here:
for(size_t x(0U); x<10U; ++x) f();