什么是“ for(const auto& s:strs){}“意思? [英] What does " for (const auto &s : strs) {} " mean?

查看:4360
本文介绍了什么是“ for(const auto& s: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){
   //
}


推荐答案

它实际上是一个C ++ 11功能,称为基于范围的for-loops。

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

case,它基本上是一个更容易写的替换:

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...
}

$ c>:是新语法的一部分 a>。

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用于确定要迭代的序列或范围。

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和end_expr定义如下:

begin_expr and end_expr are defined as follows:

如果__range是数组,则begin_expr是__range,end_expr是(__range + __bound),其中__bound是数组中元素的数量(如果数组具有未知大小,是不完整的类型,程序是不成形的)

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)

如果__range的类型是一个类型类型,具有begin或end成员函数,则begin_expr是__range.begin()和end_expr是__range.end();

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();

否则,begin_expr是begin(__ range),end_expr是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 也可以使用。

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.

这篇关于什么是“ for(const auto&amp; s:strs){}“意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆