Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a bitset on the heap in C++?

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?

like image 463
nubilot Avatar asked Aug 20 '20 15:08

nubilot


People also ask

What is BitSet in C?

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.

How much memory does BitSet use?

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[].

How large can a BitSet be?

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.


1 Answers

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].

like image 195
Bathsheba Avatar answered Sep 30 '22 10:09

Bathsheba