STL:vector<bool> 和bitset

今天某个地方要用到很多位标记于是想着可以用下bitset,不过发现居然是编译时确定空间的,不能动态分配。那就只能用vector来代替一下了,不过发现居然有vector<bool>这个特化模板,按照说明它的空间分配一般的实现就是一个元素一个bit,这就和bitset具有类似的空间效率了。另外它支持flip和一个具有不同签名的swap函数,前者将容器内所有值翻转,后者可以交换独立元素。

 

参考:

http://www.cplusplus.com/reference/vector/vector-bool/

 

class template specialization
<vector>

std::vector<bool>

template < class T, class Alloc = allocator<T> > class vector; // generic template
template <class Alloc> class vector<bool,Alloc>;               // bool specialization
Vector of bool

This is a specialized version of vector, which is used for elements of type bool and optimizes for space.

It behaves like the unspecialized version of vector, with the following changes:

  • The storage is not necessarily an array of bool values, but the library implementation may optimize storage so that each value is stored in a single bit.
  • Elements are not constructed using the allocator object, but their value is directly set on the proper bit in the internal storage.
  • Member function flip and a new signature for member swap.
  • A special member type, reference, a class that accesses individual bits in the container's internal storage with an interface that emulates a bool reference. Conversely, member type const_reference is a plain bool.
  • The pointer and iterator types used by the container are not necessarily neither pointers nor conforming iterators, although they shall simulate most of their expected behavior.


These changes provide a quirky interface to this specialization and favor memory optimization over processing (which may or may not suit your needs). In any case, it is not possible to instantiate the unspecialized template ofvector for bool directly. Workarounds to avoid this range from using a different type (charunsigned char) or container (like deque) to use wrapper types or further specialize for specific allocator types.

bitset is a class that provides a similar functionality for fixed-size arrays of bits.

posted @ 2014-04-14 08:21  卖程序的小歪  阅读(1344)  评论(0编辑  收藏  举报