[英]Ranged based for loop for vector of booleans
std::vector<bool>
uses proxy iterators. std::vector<bool>
使用代理迭代器。
So the following code will not compile (code taken from the accepted answer in related question ):因此,以下代码将无法编译(代码取自相关问题中已接受的答案):
vector<bool> v = {true, false, false, true};
for (auto& x : v)
x = !x;
In the related question, the accepted answer states that to modify the components of the vector in place, we must use在相关问题中,已接受的答案指出,要就地修改向量的分量,我们必须使用
for (auto&& x : v)
x = !x;
But if I simply do:但如果我只是这样做:
for (auto x : v)
x = !x;
This produces identical results.这会产生相同的结果。 So is the
&&
not needed?那么
&&
不需要吗?
Further why does the following 2 codes not modify the components?进一步为什么以下2个代码不修改组件?
for (bool &&x : v)
x = !x;
and和
for (bool x : v)
x = !x;
TL;DR: The proxy object knows how to read and write the single bits, regardless of how you keep it. TL;DR:代理对象知道如何读取和写入单个位,而不管您如何保留它。 Converting the proxy object to
bool
loses that information.将代理对象转换为
bool
会丢失该信息。
for (auto&& x : v)
x = !x;
and和
for (auto x : v)
x = !x;
have the same behavior because in each case the proxy object ( std::vector<bool>::reference
) obtained from dereferencing a std::vector<bool>::iterator
is stored in x
.具有相同的行为,因为在每种情况下,从解除引用
std::vector<bool>::iterator
获得的代理对象( std::vector<bool>::reference
)存储在x
。 Whether the proxy object is stored by value or reference doesn't matter - its behavior of modifying the proxied bit is the same.代理对象是按值存储还是按引用存储并不重要——它修改代理位的行为是相同的。
In在
for (bool &&x : v)
x = !x;
and和
for (bool x : v)
x = !x;
the proxy object is implicitly converted to a bool
.代理对象被隐式转换为
bool
。 This necessarily loses the information needed (and thus the capability) to affect the compressed bit.这必然会丢失影响压缩位所需的信息(以及因此的能力)。
Note that these are all implementation-defined.请注意,这些都是实现定义的。 Your implementation is allowed to forego the space optimization too, in which case the behavior you see could be different.
您的实现也可以放弃空间优化,在这种情况下,您看到的行为可能会有所不同。 Only
auto&&
works in every case.只有
auto&&
在任何情况下都有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.