vector<bool> 看起來像是一個存放布爾變量的容器,可是其實自己其實並非一個容器,它裏面存放的對象也不是布爾變量,這一點在 GCC 源碼中 vector<bool> 的註釋中寫的很清楚:java
/** * @brief A specialization of vector for booleans which offers fixed time * access to individual elements in any order. * * Note that vector<bool> does not actually meet the requirements for being * a container. This is because the reference and pointer types are not * really references and pointers to bool. See DR96 for details. @see * vector for function documentation. * * @ingroup Containers * @ingroup Sequences * * In some terminology a %vector can be described as a dynamic * C-style array, it offers fast and efficient access to individual * elements in any order and saves the user from worrying about * memory and size allocation. Subscripting ( @c [ ] ) access is * also provided as with C-style arrays. */ template<typename _Alloc> class vector<bool, _Alloc> : protected _Bvector_base<_Alloc> { // XXX: real declaration. }
C++ 標準中對容器的要求中有一條:c++
若是 c 是支持 [ ] 操做的 T 類型的容器,那麼下面的表達式必須能夠編譯:sql
\(T* p = \&c[0]\)bash
但一樣是按照 C++ 標準, vector<bool> 做爲一個單獨的對象,它裏面存放的並不是真正的 bool, 爲了節省內存,其中存放的是 bitfields ,它用其中的每個 bit 來表示 bool 。 不一樣於普通的 [ ] 操做符, vector<bool>::[ ] 返回並非 bool& ,而是一個能夠將 vector<bool> 的內部表示轉換成 bool 類型的 proxy ,因此表達式:ide
vector<bool> c; bool* p = &c[0];
不能編譯。post
因此,用到 vector<bool> 的時候,切記它並不是真正的容器,若是想用真正的存放 bool 類型的容器,需使用 deque 。ui