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

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

    You can check up to 32-bits at a time with a u64 accumulator and a 32-entry table like

    
    u32 kTable[]
    {
    0x01, 0x03, 0x07, 0x0F ..., 0xFFFFFFFF
    };
    

    Just read in 32 bits into a u64 accumulator and shift it down depending on the offset and check your bits against the table. You can do this in a binary fashion to make the number of compares at max 5. This will be slower for data that isn't 'linear' in fashion. THis then becomes log time.

提交回复
热议问题