Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add 1 to c++ bitset

Tags:

c++

boost

bitset

I have a c++ bitset of given length. I want to generate all possible combinations of this bitset for which I thought of adding 1 2^bitset.length times. How to do this? Boost library solution is also acceptable

like image 920
wirate Avatar asked Oct 23 '25 09:10

wirate


2 Answers

Try this:

/*
 * This function adds 1 to the bitset.
 *
 * Since the bitset does not natively support addition we do it manually. 
 * If XOR a bit with 1 leaves it as one then we did not overflow so we can break out
 * otherwise the bit is zero meaning it was previously one which means we have a bit 
 * overflow which must be added 1 to the next bit etc.
 */
void increment(boost::dynamic_bitset<>& bitset)
{
    for(int loop = 0;loop < bitset.count(); ++loop)
    {
        if ((bitset[loop] ^= 0x1) == 0x1)
        {    break;
        }
    }
}
like image 112
Martin York Avatar answered Oct 24 '25 21:10

Martin York


All possible combinations? Just use 64-bit unsigned integer and make your life easier.

like image 25
zvrba Avatar answered Oct 24 '25 23:10

zvrba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!