std::vector<bool>中的坑

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)

{

}

 

转载于:https://www.cnblogs.com/hustxujinkang/p/5218148.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值