for (const auto &s : strs)
是什么意思?冒号:
的作用是什么?
vector<string> &strs;
for (const auto &s : strs){
//
}
最佳答案
它实际上是一个称为“基于范围的 for 循环”的 C++11 功能。
在这种情况下,它基本上是一个更易于编写的替代品:
// 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...
}
:
是 new syntax 的一部分.
在左边,您基本上有一个变量声明,它将绑定(bind)到 vector 的元素,在右边,您有一个要迭代的变量(也称为“范围表达式”)。
以下是解释范围表达式先决条件的链接文档的摘录:
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.
请注意,多亏了所有这些,基于范围的 for 循环还支持迭代 C 数组,因为 std::begin
/std::end
也适用于这些数组。
关于c++ - "for (const auto &s : strs) {} "是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22225148/