What's the best way to store a bit array in C++ (no Boost, just standard containers), representing, for example, a volume allocation bitmap?
I thought std::vector<bool>
was a great idea, but apparently it's Evil and deprecated, so is there a better choice?
If I have a byte array in memory, how would I go about copying them to the recommended container?
(I'm having trouble figuring this out for vector<bool>
.)
The std::bitset will do, as long as your bit array is of fixed size.
As a side note there's also std::dynamic_bitset, but am not 100% sure it made it into the standard.
For vanilla C++, there's std::bitset.
Bitset is very similar to vector (also known as bit_vector): it contains a collection of bits, and provides constant-time access to each bit. There are two main differences between bitset and vector. First, the size of a bitset cannot be changed: bitset's template parameter N, which specifies the number of bits in the bitset, must be an integer constant. Second, bitset is not a Sequence; in fact, it is not an STL Container at all.
Matt Austern has a nice article on its use.
Also: If your byte array (bit array?) fits into an unsigned long, then you can assign it to a std::bitset directly:
unsigned long myByteArray = 0xABCD;
std::bitset<32> bitten( myByteArray );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With