C hack for storing a bit that takes 1 bit space?

后端 未结 5 1549
误落风尘
误落风尘 2021-02-05 18:14

I have a long list of numbers between 0 and 67600. Now I want to store them using an array that is 67600 elements long. An element is set to 1 if a number was in the set and it

5条回答
  •  星月不相逢
    2021-02-05 18:55

    You should use std::bitset.

    std::bitset functions like an array of bool (actually like std::array, since it copies by value), but only uses 1 bit of storage for each element.

    Another option is vector, which I don't recommend because:

    • It uses slower pointer indirection and heap memory to enable resizing, which you don't need.
    • That type is often maligned by standards-purists because it claims to be a standard container, but fails to adhere to the definition of a standard container*.

    *For example, a standard-conforming function could expect &container.front() to produce a pointer to the first element of any container type, which fails with std::vector. Perhaps a nitpick for your usage case, but still worth knowing about.

提交回复
热议问题