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

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

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

相关文章:

c++ - Travis CI 上 Boost 中对 `std::__cxx11::basic_string 的 undefined reference

arrays - For-Next 循环和数组 - VBA

c++ - LibXL 加载文件失败

c++ - 将 boost::variant 传递给(来自)dll 是否安全?

c++ - 与条件 noexcept 和重载不一致

c++ - 如何使 C++(共享)库与 clang 和 GCC 兼容?

python - 如何使我的 python 集成更快?

javascript - JS : Using changing String in command after "."

c++ - 将 Cpp 转换为 Rust,处理全局静态对象

c++ - 如何在 rich edit 控件中实现对 URL 的鼠标单击