c++ - Range-for-loops 和 std::vector<bool>

标签 c++ c++11 for-loop range 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;

在后一种情况下,我得到一个错误

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

for(auto& i : boolVector)

最佳答案

因为 std::vector<bool> is not a container !

std::vector<T> 的迭代器通常取消对 T& 的引用,您可以将其绑定(bind)到自己的 auto&

然而,

std::vector<bool> 将其 bool 打包在整数中,因此您需要一个代理来在访问它们时进行位掩码。因此,它的迭代器返回一个 Proxy
而且由于返回的 Proxy 是一个纯右值(一个临时值),它不能绑定(bind)到一个左值引用,例如 auto&

解决方案:使用 auto&& ,如果给定一个左值引用,它将正确折叠成一个左值引用,或者如果给定一个代理,则绑定(bind)并保持临时事件。

关于c++ - Range-for-loops 和 std::vector<bool>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079390/

相关文章:

C++ createObject() 工厂

c++ - CMake:如何确定可执行文件所需的所有 .DLL/.SO 文件?

c++ - 如何修复 "error: ‘_1’ 未在此范围内声明”?

c++ - for 循环未运行,试图向后遍历数组元素

python - 使用 Pandas 查找两个不同大小的数据帧之间的不同行

JavaScript for 循环导致 UI 无响应

c++ - 检查一系列功能的相同条件

c++ - z 顺序曲线中的下一次迭代

c++ - move 语义说明

c++ - std::tie 是否允许隐式转换?