Is there a trivial way to get 2 additions to std :: bitset <N>

I used std::bitset<N>in my program and had to find the least significant bit of the set and performed a trivial calculation, as shown below:

int num = 5;
int res = num & (-num);

Then the least significant bit is numset to res, and the rest - 0. It works as -5presented in the form of 2 add-ons.

But I found that std::bitset<N>there is no operator overload for unary operator -, which would give me 2 additions for the base bits. Is there a trivial way to implement 2 add-ons with std::bitset<N>? I could always use operator ~to flip the bits and fixate on them, making a sum and transferring it from LSB to MSB, but I was looking for a solution that would avoid this.

+5
source share
2 answers

std::bitsetdoes not provide any additional methods. Since you will need to calculate the addition with the help of operator~an additional cycle, just skip operator~()and find the LSB directly:

template <int N>
size_t least_significant_bit(const std::bitset<N> &bt){
    for(size_t i = 0; i < bt.size(); ++i){
        if(bt.test(i))
            return i;
    }
}

I think it cannot become more trivial than that.).

Note that the result is least_significant_bitnot specified if there is no bit. You can return Nor change the loop to test bt.test(N), which would throw an exception, but in the end it makes no sense to look for LSB in zero bit.

Alternatively, you can use std::bitset<N>::operator[]instead std::bitset<N>::testif you are not interested in border checks.

+2
source

- 0 , 1 0.

: ( , set [0] - , , )

int i = 0;
while (i < set.length && set[i])
  {
     set[i] = 0;
     ++i;
  }

if (i < set.length)
  set[i] = 1;
0

All Articles