Hello.

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 {
  private:
          string s;
          bitset<n> b; //now i need n = s.size().
};

How can i achieve this?
Thanks

Recommended Answers

All 4 Replies

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
public:
    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 )
                i++;
            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.

Thanks.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.