What does for (const auto &s : strs)
mean? What is the function of colon :
?
vector<string> &strs;
for (const auto &s : strs){
//
}
What does for (const auto &s : strs)
mean? What is the function of colon :
?
vector<string> &strs;
for (const auto &s : strs){
//
}
According to 6.5.4 The range-based for statement [stmt.ranged] the statement
is equivalent to
In other words, the compiler will expand it to a regular for-loop going from the
begin()
andend()
of the expression.There are some conditions about name lookup of
begin-expr
andend-expr
, but all Standard Library containers (such as yourstd::vector
),std::initializer_list
, raw arrays and anything with member or non-memberbegin()
andend()
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.It's actually a C++11 feature called "range-based for-loops".
In this case, it's basically an easier-to-write replacement for:
The
:
is part of the new syntax.On the left you basically have a variable declaration that will be bound to the elements of the vector and one the right you have the variable to iterate on (also called "range expression").
Here is an excerpt of the linked documentation that explains the prerequisites for the range-expressions:
Note that thanks to all this, range-based for loops also support iterating over C arrays as
std::begin
/std::end
works with those too.