C++11 range-based for loops without loop variable

前端 未结 10 1150
轮回少年
轮回少年 2020-12-24 04:33

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         


        
10条回答
  •  温柔的废话
    2020-12-24 05:23

    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:

    • an array or
    • a class having either
      • Member functions begin() and end() or
      • available free functions begin() 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();
    

提交回复
热议问题