Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define bitset size at initialization?

Tags:

c++

bitset

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>(); 
like image 582
Martijn Courteaux Avatar asked Jun 28 '10 17:06

Martijn Courteaux


People also ask

How do you define the size of a BitSet in C++?

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.

What is BitSet size?

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.

How much memory does BitSet use?

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

What is BitSet in programming?

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.


2 Answers

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.

like image 147
jalf Avatar answered Oct 10 '22 03:10

jalf


Use Boost::dynamic_bitset

like image 33
Thomas Jones-Low Avatar answered Oct 10 '22 03:10

Thomas Jones-Low