将 1 添加到 C++ 位集

add 1 to c++ bitset

本文关键字:C++ 位集 添加      更新时间:2023-10-16

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

试试这个:

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

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

不是最好的,而是蛮力方式,但您可以通过使用 to_ulong() 进行转换来添加 1

bitset<32> b (13);
b = b.to_ulong() + 1;

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

例如,长度为 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;
}