What is “for (x : y)”?

前端 未结 2 2006
长情又很酷
长情又很酷 2021-01-13 01:26

So i was looking around on the interwebs about threads and i came to a blog/tutorial thing about threads but what confused me was this line that he used

for          


        
相关标签:
2条回答
  • 2021-01-13 01:53

    C++11 introduced a new iteration statement, the so-called range-based for loop. It differs from the ordinary for loop in that it only gives you access to the members of a range, without requiring you to name the range itself explicitly and without using proxy iterator objects. Specifically, you are not supposed to mutate the range during the iteration, so this new loop documents the intent to "look at each range element" and not do anything complicated with the range itself.

    The syntax is this: for (decl x : r) { /* body */ }, where decl stands for some declaration and r is an arbitrary expression. This is functionally mostly equivalent to the following traditional loop:

    {
        auto && __r = r;
    
        using std::begin;
        using std::end;
    
        for (auto __it = begin(__r), __e = end(__r); __it != __e; ++__it)
        {
            decl x = *it;
            /* body */
        }
    }
    

    As a special case, arrays and braced lists are also supported natively.

    0 讨论(0)
  • 2021-01-13 02:08

    It is a C++11 range-based loop, requiring a ranged expression which may be:

    • an array or
    • braced lists
    • a class having either
      • Member functions begin() and end() or
      • available free functions begin() and end() (via ADL)

    This

    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() pair. (The statement may be a compund statement in curly braces.)

    0 讨论(0)
提交回复
热议问题