Efficient way of iterating over true bits in std::bitset?

后端 未结 6 1700
旧巷少年郎
旧巷少年郎 2020-12-14 16:29

Is there a way of iterating over a (possibly huge) std::bitset that is linear in the number of bits that are set to true? I want to prevent ha

6条回答
  •  攒了一身酷
    2020-12-14 17:33

    There are only two options that do much better than O(N) on total bits:

    1. Using specialty bit-scan instructions available in certain architectures like BSF in x86.
    2. There are O(log2(N)) algorithms for finding the lowest bit set in a word. This, of course does not scale well when the bitset is dense, rather than sparse. Resurrecting some foggy memory of mine, I found the source in the FXT library Details can be found in the FXT book (pdf), in section 1.3.2.

提交回复
热议问题