将1添加到c ++ bitset

时间:2012-04-28 11:17:13

标签: c++ boost bitset

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

3 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:2)

所有可能的组合?只需使用64位无符号整数,让您的生活更轻松。

答案 2 :(得分:0)

使用boost库,您可以尝试以下操作:

例如,长度为4的位集

boost::dynamic_bitset<> bitset;
for (int i = 0; i < pow(2.0, 4); i++) {
    bitset = boost::dynamic_bitset<>(4, i);

    std::cout << bitset << std::endl;

}