范围for循环和std :: vector< bool> [英] Range-for-loops and std::vector<bool>
问题描述
为什么这个代码可以工作
std :: vector< int> intVector的(10); (auto& i:intVector)
std :: cout<<一世;
而这不是吗?
的std ::矢量< BOOL> boolVector(10); (auto& i:boolVector)
std :: cout<<一世;
在后一种情况下,我得到一个错误
错误:类型为'std :: _ Bit_iterator :: reference {aka std :: _ Bit_reference}'的右值类型为'std :: _ Bit_reference&'的非const引用无效初始化
for(auto& i:boolVector)
std :: vector< T>
的迭代器通常取消引用 T&
可绑定到自己的 auto&
。
$ b
解决方案:use Why does this code work And this doesn't? In the latter case, I get an error error: invalid initialization of non-const reference of type ‘std::_Bit_reference&’ from an rvalue of type ‘std::_Bit_iterator::reference {aka std::_Bit_reference}’
Because The solution : use 这篇关于范围for循环和std :: vector< bool>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! std :: vector< bool> / code>,然而,将它的
bool
s整合在一起,所以你需要一个代理在访问时进行位掩码。因此,它的迭代器返回代理
。
并且由于返回的代理
是一个prvalue一个临时的),它不能绑定到一个左值引用,如 auto&
。
auto&&
,如果给定一个,它将正确地折叠成一个左值引用,或者在给定代理的情况下绑定和维护临时存活。std::vector<int> intVector(10);
for(auto& i : intVector)
std::cout << i;
std::vector<bool> boolVector(10);
for(auto& i : boolVector)
std::cout << i;
for(auto& i : boolVector)
std::vector<bool>
is not a container !std::vector<T>
's iterators usually dereference to a T&
, which you can bind to your own auto&
.std::vector<bool>
, however, packs its bool
s together inside integers, so you need a proxy to do the bit-masking when accessing them. Thus, its iterators return a Proxy
.
And since the returned Proxy
is an prvalue (a temporary), it cannot bind to an lvalue reference such as auto&
.auto&&
, which will correctly collapse into an lvalue reference if given one, or bind and maintain the temporary alive if it's given a proxy.