i needed a variable size bit string. And since bitset provides several operations, i wanted to use it. But is it possible to make it a variable size one?

class TryBits {
          string s;
          bitset<n> b; //now i need n = s.size().

How can i achieve this?

7 Years
Discussion Span
Last Post by myk45

I think the best way to achieve this is to wrap the functionality of a bitset with custom functions.

So, to extend your bitset:

class TryBits
// whatever other functionality
    extend( const string& ns )
        // insert a check for ns to be a valid bit string.
        //  i.e. only 1s and 0s
        s += ns;
        b = bitset< s.size() >( s );
    append( bool nbit )
        bitset< b.count() + 1 > nb;
        for( int i=0; i<b.count(); i++ )
            nb[i] = b[i];
        nb[ b.count() ] = nbit;
        b = nb;
    void remove( int index )
        // check boundary conditions     
        bitset< b.count() - 1 > nb;
        for( int i=0, j=0; i<b.count(); i++, j++ )
            if( i == index )
            nb[j] = b[i];
        b = nb;

I haven't tested any of this, but I think you could proceed with this kind of an idea. You would probably want to add in a setSize( int n ) function as well.


Thanks for the reply dusktreader.
But the problem was, how shall i declare the private member b as?

bitset<2> b;

b = bitset<4> ("1101");
gives compilation error. So, how can i declare my private member, since there is a requirement for a constant to be present.



Hmmm.... I see the problem. How asinine to make the bitset size controlled by a template parameter.

I think you could go down two roads.

First, you could store your bits in the string exclusively and return a specific bitset when asked:

template <int bsize>
bitset<bsize> getBits()
    return bitset<bsize> bits( s );

I would personally favor using a vector<bool>. Of course, you'll have to implement your own logic. This would provide all the extensibility you would need.


Thanks. i think vector<bool> would be a better option for me, although i would have to add functionality to it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.