问题描述
Scott Meyers 的书 Effective STL: 50 Specific Ways to改善标准模板库使用的第 18 条 说要避免 vector
因为它不是一个STL 容器,它并没有真正保存 bool
s.
Item 18 of Scott Meyers's book Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library says to avoid vector <bool>
as it's not an STL container and it doesn't really hold bool
s.
以下代码:
vector <bool> v;
bool *pb =&v[0];
不会编译,违反 STL 容器的要求.
will not compile, violating a requirement of STL containers.
错误:
cannot convert 'std::vector<bool>::reference* {aka std::_Bit_reference*}' to 'bool*' in initialization
vector
返回类型应该是 T&
,但为什么它是 vector
?
vector<T>::operator []
return type is supposed to be T&
, but why is it a special case for vector<bool>
?
vector
究竟由什么组成?
该项目进一步说明:
deque<bool> v; // is a STL container and it really contains bools
这可以用作 vector
的替代品吗?
Can this be used as an alternative to vector<bool>
?
谁能解释一下?
推荐答案
出于空间优化的原因,C++ 标准(最早可追溯到 C++98)明确调用了vector
作为一个特殊的标准容器,其中每个 bool 只使用一位空间,而不是像普通 bool 那样使用一个字节(实现一种动态位集").作为这种优化的交换,它没有提供普通标准容器的所有功能和接口.
For space-optimization reasons, the C++ standard (as far back as C++98) explicitly calls out vector<bool>
as a special standard container where each bool uses only one bit of space rather than one byte as a normal bool would (implementing a kind of "dynamic bitset"). In exchange for this optimization it doesn't offer all the capabilities and interface of a normal standard container.
在这种情况下,因为你不能在一个字节中取一个位的地址,所以诸如 operator[]
之类的东西不能返回 bool&
但是而是返回一个代理对象,该对象允许操作有问题的特定位.由于此代理对象不是 bool&
,因此您无法将其地址分配给 bool*
,就像在正常"容器.反过来,这意味着 bool *pb =&v[0];
不是有效代码.
In this case, since you can't take the address of a bit within a byte, things such as operator[]
can't return a bool&
but instead return a proxy object that allows to manipulate the particular bit in question. Since this proxy object is not a bool&
, you can't assign its address to a bool*
like you could with the result of such an operator call on a "normal" container. In turn this means that bool *pb =&v[0];
isn't valid code.
另一方面,deque
没有任何这样的特化,所以每个 bool 需要一个字节,你可以从 operator[]
.
On the other hand deque
doesn't have any such specialization called out so each bool takes a byte and you can take the address of the value return from operator[]
.
最后请注意,MS 标准库的实现(可以说)不是最理想的,因为它对双端队列使用了较小的块大小,这意味着使用双端队列作为替代并不总是正确的答案.
Finally note that the MS standard library implementation is (arguably) suboptimal in that it uses a small chunk size for deques, which means that using deque as a substitute isn't always the right answer.
这篇关于为什么不是 vector<bool>STL 容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!