Range-for-loops and std::vectorlt;boolgt;(Range-for-loops 和 std::vectorbool;)
问题描述
为什么这段代码有效
std::vector<int> intVector(10);
for(auto& i : intVector)
std::cout << i;
这不是吗?
std::vector<bool> boolVector(10);
for(auto& i : boolVector)
std::cout << i;
在后一种情况下,我得到一个错误
In the latter case, I get an error
错误:从std::_Bit_iterator::reference {aka std::_Bit_reference}"类型的右值对std::_Bit_reference&"类型的非常量引用进行无效初始化
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>
不是容器 !
Because std::vector<bool>
is not a container !
std::vector<T>
的迭代器通常取消对 T&
的引用,您可以将其绑定到自己的 auto&
.
std::vector<T>
's iterators usually dereference to a T&
, which you can bind to your own auto&
.
std::vector<bool>
将其 bool
打包在整数中,因此您需要代理在访问它们时进行位掩码.因此,它的迭代器返回一个 Proxy
.
并且由于返回的 Proxy
是一个纯右值(一个临时的),它不能绑定到一个左值引用,例如 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&&
,如果给定一个左值引用,它将正确折叠成一个左值引用,或者如果给定一个代理,则绑定并保持临时活动.
The solution : use 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.
这篇关于Range-for-loops 和 std::vector<bool>;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Range-for-loops 和 std::vector<bool>;
基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01