将1添加到c ++ bitset

问题描述 投票:2回答:3

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

c++ boost bitset
3个回答
2
投票

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


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;
        }
    }
}

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;

}
© www.soinside.com 2019 - 2024. All rights reserved.