Bitset in C++, about continuously add

前端 未结 2 452
鱼传尺愫
鱼传尺愫 2021-01-24 16:02

I want to add 1 value to the bitset until it over flows, I am wondering how to do this, like:

bitset<20> foo; (foo=00000 00000 00000 00000) how can we implement thi

2条回答
  •  孤街浪徒
    2021-01-24 16:27

    You may use the following: http://ideone.com/C8O8Qe

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

    And then to iterate on all values :

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

提交回复
热议问题