关于 vector<bool>

结论:尽量避免使用vector<bool>,可以用dequebitset替代


官方说明

STL文档中对vector<bool>的说明:

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 of vector for bool directly.

Workarounds to avoid this range from using a different type (char, unsigned 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.


简单解释

vector<bool>实际是一个伪容器,并不保存真正的bool,而是打包bool以节省空间。

因此使用operator[]取到的并不是对元素的引用,而是vector< bool>:reference的对象。

1
2
vector<bool> x = {true, true, true, false};
bool *p = &x[0];

会报错:

taking address of temporary [-fpermissive]

如果一定要使用vctor<bool>的话,应该不要使用下标的方式进行访问,应当使用迭代器或者vector提供的其他函数进行使用,以免出现上述意想不到的结果。