std::vector<bool>
cppreference std::vector<bool>
std::vector<bool>
is not a container
在阅读boost iterator的Standard Proposal For New-Style Iterators (PDF)时,其中有关于std::vector<bool>
的这样的描述:
For example,
vector<bool>::iterator
is almost a random access iterator, but the return type is notbool&
(see issue 96 and Herb Sutter's paper J16/99-0008 = WG21 N1185). Therefore, the iterators ofvector<bool>
only meet the requirements of input iterator and output iterator.
在下面文章中对此进行了解释:
stackoverflow Why is vector not a STL container?
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 abool&
but instead return a proxy object that allows to manipulate the particular bit in question. Since this proxy object is not abool&
, you can't assign its address to abool*
like you could with the result of such an operator call on a "normal" container. In turn this means thatbool *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 fromoperator[]
.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.