The heck of vector of bool specialization





5.00/5 (4 votes)
A glance around vector of bool-type
This is surely not a Tip/Trick, rather this is about understanding the peculiarity of vector<bool>, so that one can avoid certain pitfalls.
For the
bool
type, the vector container is specialized to store the Boolean values as bits rather than as values. This is done to achieve space optimization - instead of having 8 bits, it will use just 1 bit.
But this pre-determined optimization leads to few unwanted results.
- For example, this code won't compile.
vector<bool> _vec; _vec.push_back(true); _vec.push_back(false); bool& b = _vec.front(); // This line is the culprit
But the same works fine if we havevector<short>
or any other data type. This is because the functions likefront()
,back()
return references and there are no pointers/references for bits (remembervector<bool>
stores values as bits). The workaround is to use a special member called reference:vector<bool>::reference b = _vec.front();
One way to solve this premature optimization is to provide our own allocator:vector<bool, NewAllocator> _vec
or usevector<char>
instead. But this requires un-necessarybool-char
conversions. - This special type has a special function
flip()
for reversing the bits - thus providing a different interface rather than following the interface of other related containers. Seeing all these, the trick is to avoid usingvector<bool>
totally - Anyway, it is deprecated and is going to be kicked out of the STL soon.