I want to make a bitset in C++. I did a bit of research. All examples I found where like this:
bitset<6> myBitset; // do something with it
But I don't know the size of the bitset when I define the variable in my class:
#include <bitset> class Test { public: std::bitset *myBitset; }
This won't compile...
And initializing like this also doesn't work:
int size = getDependentSizeForBitset(); myBitset = new bitset<size>();
bitset::size() is a built-in STL in C++ which returns the total number of bits. Parameter: The function accepts no parameter. Return Value: The function returns an integral value which signifies the number of bits. It eventually returns the size that has been given while initializing the bitset.
size() method returns the number of bits of space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element.
Therefore, if we need a vector of bits, boolean[] will have a pretty significant memory footprint. As shown above, this boolean[] consumes around 10 KB of memory. As expected, the BitSet with the same number of bits consumes around 1 KB, which is far less than the boolean[].
Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.
Boost has a dynamic_bitset
you can use.
Alternatively, you can use a vector<bool>
, which (unfortunately) is specialized to act as a bitset. This causes a lot of confusion, and in general is considered a bad idea. But that's how it works, so if that's what you need, you might as well use it, I suppose.
Use Boost::dynamic_bitset
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