What does “ for (const auto &s : strs) {} ” mean?

后端 未结 2 823
执笔经年
执笔经年 2020-12-10 08:37

What does for (const auto &s : strs) mean? What is the function of colon :?

vector &strs;
for (const auto &a         


        
2条回答
  •  醉酒成梦
    2020-12-10 09:12

    According to 6.5.4 The range-based for statement [stmt.ranged] the statement

    for ( for-range-declaration : expression ) statement
    

    is equivalent to

    {
        auto && __range = range-init;
        for (auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) {
           for-range-declaration = *__begin;
           statement
        }
    }
    

    In other words, the compiler will expand it to a regular for-loop going from the begin() and end() of the expression.

    There are some conditions about name lookup of begin-expr and end-expr, but all Standard Library containers (such as your std::vector), std::initializer_list, raw arrays and anything with member or non-member begin() and end() functions in the right namespace will be accepted.

    The : is simply the syntax to separate the declaration of what you use inside the loop from the expression which you loop over.

提交回复
热议问题