本文介绍了为什么vector< bool>一个STL容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scott Meyers的书中的第18条有效的STL:改进对标准模板库的使用的50种特定方法说避免使用 vector< bool> ,因为它不是STL容器,并且实际上并不容纳 bool s。



以下代码:

  vector< bool> v; 
bool * pb =&v [0];

不会编译,这违反了STL容器的要求。



错误:

 无法转换'std :: vector< bool> :: reference * {aka std :: _Bit_reference *}'初始化为

vector< T> :: operator [] 返回类型应该是 T& ,但是为什么它是 vector<的特殊情况? bool>



vector< bool> 到底由什么组成?

该项目还说:

  deque< bool> v; //是一个STL容器,它实际上包含布尔

是否可以用作<$的替代c $ c> vector< bool> ?



有人可以解释吗?

解决方案

出于空间优化的原因,C ++标准(最早可追溯至C ++ 98)明确调用 vector< bool> 作为特殊的标准容器,其中每个布尔仅使用一个空间位,而不是普通布尔所使用的一个字节(实现一种动态位集)。作为这种优化的交换,它没有提供普通标准容器的所有功能和接口。



在这种情况下,因为您不能使用a的地址在一个字节内,例如 operator [] 之类的内容不能返回 bool& ,而是返回一个代理对象这样就可以操纵相关的特定位。由于此代理对象不是 bool& ,因此无法像其可能的那样将其地址分配给 bool * 这样的结果就是操作员在普通容器上调用。反过来,这意味着 bool * pb =& v [0]; 无效。



另一方面, deque 没有任何这样的特殊化,因此每个布尔值都占用一个字节,您可以从中获取值返回的地址。最后请注意,MS标准库实现(可以说)不是最优的,因为它使用较小的块大小进行双端队列,这意味着使用双端队列代替并不总是正确的答案。


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 bools.

The following code:

vector <bool> v;
bool *pb =&v[0];

will not compile, violating a requirement of STL containers.

Error:

cannot convert 'std::vector<bool>::reference* {aka std::_Bit_reference*}' to 'bool*' in initialization

vector<T>::operator [] return type is supposed to be T&, but why is it a special case for vector<bool>?

What does vector<bool> really consist of?

The Item further says:

deque<bool> v; // is a STL container and it really contains bools

Can this be used as an alternative to vector<bool>?

Can anyone please explain this?

解决方案

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.

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.

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[].

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&lt; bool&gt;一个STL容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:52