C++中的位集,关于连续添加

Bitset in C++, about continuously add

本文关键字:连续 添加 于连续 C++      更新时间:2023-10-16

我想向比特集添加1个值,直到它溢出,我想知道如何做到这一点,比如:

位集<20> foo;(foo=000000000000000000000)我们如何实现这个功能,连续添加一个

00000000000000000000>00000000000000000001>000000000000000000000000>00010>000000000000000000000000011,直到溢出?

我正在考虑两种方式;

foo.to_ulong();

如何将无符号长再次转换回位集?C++文档表明这是可能的,但在库中,我只能看到位集(无符号长val),它正在创建一个新的位集

2。不知怎的,位操作都被卡住了,需要的帮助

您可以使用以下内容:http://ideone.com/C8O8Qe

template <std::size_t N>
bool increase(std::bitset<N>& bs)
{
    for (std::size_t i = 0; i != bs.size(); ++i) {
        if (bs.flip(i).test(i) == true) {
            return true;
        }
    }
    return false; // overflow
}

然后迭代所有值:

std::bitset<20> bs;
do {
    std::cout << bs << std::endl;
} while (increase(bs));

以下代码应该会对您有所帮助:

bitset<20> b;
bool overflow = false;
while( ! overflow ){
    cout << b << endl; // prints bits in reversed order
    int ipos = b.size();
    overflow = true;
    while( overflow && --ipos >= 0 ){ 
        overflow = b[ipos];
        b[ipos] = ! b[ipos];
    }
}

由@Jarod42测试,谢谢。