I\'m working with a user-defined quantity of bits (I\'m holding a three-dimensional array of bits, so the size increases cubically - assume no less then 512 bits), and need
There's nothing wrong with correct usage of vector<bool>
, just like there's nothing wrong with auto_ptr
- as long as you know the drawbacks and the surprises before going on.
There is boost.dynamic_bitset which is nearly identical to std::bitset, except that its size is given at runtime. If you're not interested in boost dependency, its source code (which is entirely contained in its header file) could at least give more ideas on how such container could be written.
In "Effective STL," Item 18, Scott Meyers recommended: "Avoid using vector< bool >.":
As an STL container, there are really only two things wrong with vector< bool >. First, it's not an STL container. Second, it doesn't hold bools. Other than that, there's not much to object to.
There's nothing wrong with vector<bool>
, except that it isn't equivalent to a vector<T>
were T is the integer type equivalent to bool. This only shows in performance (CPUs only access bytes at a time, where in a vector<bool>
every element is stored in one bit) and memory access (a reference to a first element of a vector<bool>
is not equivalent to an array like with any other vector<T>
.
It is part of the Standard, unfortunately: see section 23.3.7
(C++0x FDIS).
The critique is that vector<bool>
is the only standard container that doesn't fully conform to the standard's container requirements. That's a bit of a surprise.
Another point is that vector<bool>
forces a space optimization on everyone (by storing bits), when perhaps some users would have preferred a speed optimization.
Other than that, the major deviation is that the container cannot return a reference to its members, because it doesn't store any bools. That will make the odd standard library algorithm fail to compile for vector<bool>
.
If you can live with that, and it fits your needs for everything else, it is quite ok to use it.
An alternative could be BitMagic although I'm not sure it works on any other architecture than x86(it's heavily optimized using SIMD).