C ++: creating an iterator from bits

I have a bitmap and would like to return an iterator of the positions of the given bits. Right now, I am just going through the entire bitmap, and if the bit is set, I provide the following position. I believe that this could be done more efficiently: for example, build a static array for each combination of bits in one byte and a position return vector. This cannot be done for an int, because the array will be too large. But maybe there are some better solutions? Do you know any smart algorithms for this?

+3
source share
1 answer

I can offer some ideas.

  • , 32- 64- .
  • - , , , !
  • , - , , , .
  • , ( , , ), (32- 64-) .
  • , , heapsort. , , "", (N + 1) [i] = (N) [2 * i] | () [2 * + 1]. , , . , ..: , .
  • ; ., , code java:
  • , , t.i. begin() operator ++(), foreach (F) , F (). , F operator() , , .

EDIT: . # 2.0, :

IEnumerable<int> bits(byte[] bytes) {
    for(int i=0; i<bytes.Length; ++i) {
        int oi=8*i;
        switch(bytes[i]) {
            ....
            case 74: yield return oi+1; yield return oi+4; yield return oi+6; break;
            ....
        }
    }
}

50% (10 ) , :

for (int i = 0; i < bytes.Length; ++i) {
    byte b = bytes[i];
    for (int j = 7; j >= 0; --j) {
        if (((int)b & (1 << j)) != 0) s++;
    }
}

1,66 (~ 1.5s ~ 2.5s). , - .

+5

Source: https://habr.com/ru/post/1735775/


All Articles