将1添加到c ++ bitset

wir*_*ate 2 c++ boost bitset

我有一个给定长度的c ++ bitset.我想生成这个bitset的所有可能组合,我想添加1 2 ^ bitset.length次.这该怎么做?Boost库解决方案也是可以接受的

Mar*_*ork 5

试试这个:

/*
 * 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)