强制自动成为循环范围内的引用类型 [英] Forcing auto to be a reference type in a range for loop
问题描述
假设我有 foo
这是一个填充的 std :: vector< double>
。
我需要对这个向量的元素进行操作。我有动力写下
for(auto it:foo){
/ * ToDo - Operate on'it '* /
}
但看起来这不会写回 foo
因为 it
是一个值类型:已经采用了向量元素的深拷贝。
我可以给 auto
一些指导,使 it
引用类型吗?然后我可以直接在 it
上进行操作。
我怀疑我缺少一些微不足道的语法。
最少自动
参考 b
$ b
循环可以声明如下:
for(auto& it:foo) {
// ^附加&需要
/ * ToDo - 操作'it'* /
}
这将允许 it
是对 foo
中每个元素的引用。
对于这些循环的规范形式有一些争论,但 auto&
在这种情况下应该做。
一般自动
参考
一个更一般的意义(在容器的细节之外),以下循环工作(并且可能是更好的)。
(auto&& it:container){
// ^&&用于此处
}
自动& c $ c>允许绑定到左值和右值。当在一般或一般(例如模板情况)中使用时,这种形式可以达到期望的平衡(即引用,副本,prvalue / xvalue返回(例如代理对象)等)。
喜欢一般的 auto&&&
,但如果您必须具体说明表单,请使用更具体的变体(例如 auto
为什么<$ <$ p $ <$> c $ c> auto&&&< / code>更好?
为什么 auto&&&
更好?只要它会做你认为它应该在大多数情况下,看到此提案和其更新。
Suppose I have foo
which is a populated std::vector<double>
.
I need to operate on the elements of this vector. I'm motivated to write
for (auto it : foo){
/*ToDo - Operate on 'it'*/
}
But it appears that this will not write back to foo
since it
is a value type: a deep copy of the vector element has been taken.
Can I give some guidance to auto
to make it
a reference type? Then I could operate directly on it
.
I suspect I'm missing some trivial syntax.
A minimal auto
reference
The loop can be declared as follows:
for (auto& it : foo) {
// ^ the additional & is needed
/*ToDo - Operate on 'it'*/
}
This will allow it
to be a reference to each element in foo
.
There is some debate as to the "canonical form" of these loops, but the auto&
should do the trick in this case.
General auto
reference
In a more general sense (outside the specifics of the container), the following loop works (and may well be preferable).
for (auto&& it : container) {
// ^ && used here
}
The auto&&
allows for bindings to lvalues and rvalues. When used in a generic or general (e.g. template situation) this form may strike the desired balance (i.e. references, copies, prvalue/xvalue returns (e.g. proxy objects) etc.).
Favour the general auto&&
, but if you have to be specific about the form, then use a more specific variation (e.g. auto
, auto const&
etc.).
Why is auto&&
better?
As noted in other answers here and the comments. Why is auto&&
better? Simply it will do what you think it should in most cases, see this proposal and its update.
As always, Scott Meyers' blog about this also makes for a good read.
这篇关于强制自动成为循环范围内的引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!