Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c++ - What does " for (const auto &s : strs) {} " mean?

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

vector<string> &strs;
for (const auto &s : strs){
   //
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's actually a C++11 feature called "range-based for-loops".

In this case, it's basically an easier-to-write replacement for:

// Let's assume this vector is not empty.
vector<string> strs;

const vector<string>::iterator end_it = strs.end();

for (vector<string>::iterator it = strs.begin(); it != end_it; ++it) {
  const string& s = *it;
  // Some code here...
}

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:

range_expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and assigned to the variable with the type and name given in range_declaration.

begin_expr and end_expr are defined as follows:

If __range is an array, then begin_expr is __range and end_expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed)

If __range's type is a class type with either or both a begin or an end member function, then begin_expr is __range.begin() and end_expr is __range.end();

Otherwise, begin_expr is begin(__range) and end_expr is end(__range), which are found via argument-dependent lookup with std as an associated namespace.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...