I’ve read in a lot of places that a set data structure can be implemented in C++ using a bit array, but I don’t fully understand this and haven’t been able to find a code sample. Does anyone have an example or a detailed explanation?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using a bit field to implement a set only works if there are only a few possible elements that can go in the set, because you need a bit for each of them. A bit-set of all 32-bit integers, for instance, would need 2^32 bits, or about 500 megabytes.
The good news is, if there are few enough possible elements that space isn’t a problem, it’s really, really fast.
What you do, essentially, is define a bit array such that each bit corresponds to one possible element. Each bit corresponding to an element that’s in the set is 1; the others are 0.
Will post sample C code in a bit (no pun intended). I think C++ may offer direct library support for bit-sets, but unfortunately I don’t speak it.
EDIT: The following sample code, which I just wrote, is for a bit-set which can contain the numbers 0 through 31. Allowing support for an arbitrary number of elements would be significantly more complicated, though certainly useful.