http://www.cplusplus.com/reference/vector/vector/?kw=vector
C++中,vector<bool>為了達到節省內存的目的,專門做了特化,大概方式就是用bit位來存儲數組中的元素。代價就是,這個容器里面的內置類型亂掉了:
member type definition notes value_type The first template parameter (bool) allocator_type The second template parameter (Alloc) defaults to: allocator<bool> reference A specific member class (see reference below) const_reference bool pointer a type that simulates pointer behavior convertible to const_pointer const_pointer a type that simulates pointer to const behavior iterator a type that simulates random access iterator behavior convertible to const_iterator const_iterator a type that simulates random access iterator to const behavior reverse_iterator reverse_iterator<iterator> const_reverse_iterator reverse_iterator<const_iterator> difference_type a signed integral type usually the same as ptrdiff_t size_type an unsigned integral type usually the same as size_t
比較常見的問題是,reference 類型的問題(注意這里const_reference的類型是bool,跟reference不一樣,簡直奇葩)
vector<bool> a;
a[0];//類型並不是bool!!!
由於定義了operator bool(),一般會有隱式類型轉換,所以不易察覺。
但是在某些情況下,比如模板,auto自動類型推導里面,得到的類型是嚴格的類型,不會做轉換,這時候就有可能出問題,比如下面這段代碼:
auto b = a[0];
for(const auto& c : a)
{
}