for循环c ++中的'冒号'和'自动'?需要一些帮助来理解语法 [英] 'colon' and 'auto' in for loop c++? need some help understanding the syntax

查看:192
本文介绍了for循环c ++中的'冒号'和'自动'?需要一些帮助来理解语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对以下c ++语法进行一些解释:

I need some explanation for the following c++ syntax:

for(const auto& ioDev : deviceList)

鉴于:

std::vector<Device *> deviceList

具体来说,我对':'和'auto'的用法感到困惑?

Specifically, I am confused about ':' and the usage of 'auto'?

推荐答案

如乍得的答案所述,您的for循环遍历 vector ,使用其开始 end 迭代器。这就是冒号语法的行为。

As described in the answer by Chad, your for-loop iterates over your vector, using its begin and end iterators. That is the behavior of the colon : syntax.

关于 const auto& 语法:您应该想象从中得到什么代码:

Regarding your const auto & syntax: you should imagine what code comes out of it:

// "i" is an iterator
const auto& ioDev = *i;

* i 的表达式是(一个引用容器中元素的类型:设备* 。这是 auto 的推导类型。因为您在 auto 后面附加了 const& ,所以变量 ioDev 是对推断类型(指针)的 const 引用,就好像是这样声明的:

The expression *i is (a reference to) the type of elements in the container: Device *. This is the deduced type of auto. Because you have const & appended to your auto, the variable ioDev is a const reference to the deduced type (a pointer), as if it were declared this way:

const Device *& ioDev = *i;

似乎不必要的复杂;如果只需要普通迭代(而不是例如操纵指针的地址,我认为这种可能性很小),请使用普通的未修改的 auto

It seems needlessly complicated; if you need just normal iteration (and not e.g. manipulating the address of the pointer, which I think is highly unlikely), use a plain unmodified auto:

for (auto ioDev : deviceList)

或显式类型:

for (Device* ioDev : deviceList)

这篇关于for循环c ++中的'冒号'和'自动'?需要一些帮助来理解语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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