zoukankan      html  css  js  c++  java
  • 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)

    {

    }

  • 相关阅读:
    数据结构习题
    POJ 2965 The Pilots Brothers' refrigerator
    POJ 1753 Flip Game
    HDU 1172 猜数字
    假币问题
    HDU 1425 sort
    Java基础知识
    P1650 田忌赛马
    SQL注入之Sqli-labs系列第十九关(基于头部的Referer POST报错注入)
    SQL注入之Sqli-labs系列第十八关(基于错误的用户代理,头部POST注入)
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/5218148.html
Copyright © 2011-2022 走看看