std::vectorbool

Started by
5 comments, last by TheFallenKing 18 years, 10 months ago
I've read that std::vector<bool> is a special case that can be used as a bitvector. Well that's great because I need a bit vector for a small tool I'm building. But I can't find anything examples or explanations of how to use it as a bit vector (the documentation is pretty vague). Can anyone point me in the right direction?
Advertisement
You don't have to do anything. [grin]
If you want to use a std::bitset (which is basically a vector of bools), take a look at this post.
std::vector<bool> is a specialization of std::vector<T>, which means it'll be used automatically whenever the template argument is "bool". std::bitset is similar to std::vector<bool>, but is not growable.

It bears mentioning, by the way, that many consider the specialization of std::vector<bool> to be a Very Bad Thing; this "feature" may well be deprecated in a future version of C++.
You just use it as you would any normal vector:

std::vector< bool > some_bits;some_bits.resize( 20 ); //20 bits...some_bits[0] = true;some_bits[1] = false;bool a_bit = some_bits[19];


std::vector< bool > is often specialized to take only (on an x86 anyways) 1 byte per 8 bools (e.g. the data is compacted). Many consider this to be a serious flaw, as it means you can't write code like:

bool & a_bit = some_bits[13];
a_bit = 4;

And have it reliably work on an ISO Compliant compiler, since pointers/references only have the granularity of a byte (e.g. the minimum you can increment a pointer by is 8 bits at a time).

If you have a fixed-size bitset, you should be using std::bitset (MSDN documentation). If you need a variable-size bitset that will conserve memory, you should, IMO, use boost::dynamic_bitset in favor of std::vector< bool > - AFAIK, although certain requirements are removed for std::vector< bool > soas to allow for memory saving compression, it is not mandated that std::vector< bool > be a specialization - the fact that there appears to be no specialization in the GNU ISO C++ Library (as of Apr 27, 2005 anyways, judging by the doxygen timestamp on this page, at the bottom of which has links to the sources which I checked for such a specialization) seems to collaborate this.
Quote:Original post by Drew_Benton
If you want to use a std::bitset (which is basically a vector of bools), take a look at this post.


However bitset cannot change its size at runtime, although vector of bools maybe okay, not only does it not have the nice functionality/interface of bitset it has *serious issues* in the actual standard itself which will be resolved by the C++ standards committee at some point in time.

Until then you need a C++ Boost try out dynamic_bitset
I will look into Boost's dynamic_bitset since that is exactly what I'm in need of :)

This topic is closed to new replies.

Advertisement