If i use a bitset on the stack i can do the following:
std::bitset<8> bset_s;
bset_s.flip(1);
std::cout << "Bitset on stack: " << bset_s << std::endl;
std::cout << "Element 1: " << bset_s[1] << std::endl;
Output:
Bitset on stack: 00000010
Element 1: 1
But when I try to allocate the bitset on the heap:
std::bitset<8> * bset;
bset = new std::bitset<8>;
bset->flip(1);
std::cout << "Bitset on heap: " << * bset << std::endl;
std::cout << "Element 1: " << bset[1] << std::endl;
Output:
Bitset on heap: 00000010
Element 1: 00000000
I get an empty Bitset instead of "1" if I try to access the second bit. What am I doing wrong?
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.
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[].
The size() method of Java BitSet class returns the total number of bit space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element. The default size of the bit set is 64-bit space.
bset[1]
is equivalent to *(bset + 1)
as bset
is a pointer. This is dereferencing memory that you don't own, so the behaviour of the program is undefined.
You need (*bset)[1]
.
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