Define bitset size at initialization?

Martijn Courteaux picture Martijn Courteaux · Jun 28, 2010 · Viewed 25.2k times · Source

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>();

Answer

jalf picture jalf · Jun 28, 2010

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.