c++ - "for (const auto &s : strs) {} "是什么意思?

标签 c++ c++11 for-loop stl range

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/

相关文章:

c++ - 与for循环中的变量混淆

c++ - 柏林噪声生成

c++ - 如何将程序的句柄赋予它创建的进程?

c++ - 为什么函数默认参数不能在C++中完美转发?

c++ - 如何启用 VS2013 c++ 编译器功能?

r - 修复更新和检查更新数据条件的循环

具有两个结构的 C 迭代

c++ - _sopen_s 如何管理对同一文件的多次写入

c++ - 是否可以修改现有类中的 or "customize"运算符?

c++ - header 一定是文件吗?