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)
{
}
时间: 2024-10-16 12:41:15