为什么不是vector<bool>STL 容器?
Scott Meyers 的书Effective STL: 50 Specific Ways to Improvement Your Use of the Standard Template Library 的第 18 项说要避免使用 vector <bool>
,因为它不是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>::operator []
返回类型应该是T&
,但是为什么是vector
vector<T>::operator []
return type is supposed to be T&
, but why is it a special case for vector<bool>
?
vector<bool>
真正由什么组成?
物品进一步说:
deque<bool> v; // is a STL container and it really contains bools
这可以用作 vector<bool>
的替代品吗?
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 标准库的实现(可以说)是次优的,因为它为 deques 使用了较小的块大小,这意味着使用 deque 作为替代品并不总是正确的答案.
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.
相关文章