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

后端 未结 6 1703
旧巷少年郎
旧巷少年郎 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:16

    Sometimes people use run-length encoding for things like that. If you encode incoming bitset into an array of run lengths the number of runs you end up with wouldn't exceed the number of transitions between set and clear bits, which is at most 2*k. Furthermore, in many applications the number of transitions is much less than k, so you'd get excellent average time performance in addition to linear worst-case one.

    Furthermore, it's straightforward to add a data structure that would let you efficiently search for things such as "the next set bit starting with nth position in the array": just build a scan of run lengths.

提交回复
热议问题