Search code examples
c++vectorbooleanbitsetstl-algorithm

Converting Between std::bitset and std::vector<bool>


I have a std::bitset but now I want to use an STL algorithm on it.

I could have used std::vector<bool> instead, but I like std::bitset's constructor and I want std::bitset's bitwise operations.

Do I have to go through a loop and stuff everything in a std::vector<bool> to use STL algorithms, and then copy that back to the std::bitset, or is there a better way?


Solution

  • Matthew Austern wrote an iterator for bitset here: http://www.drdobbs.com/the-standard-librarian-bitsets-and-bit-v/184401382?pgno=2

    It's over 100 lines so I feel just lifting it and putting it in this answer may be a bit out of bounds. But it works marvelously for STL algorithms.

    Austern answers this exact question:

    While bitset doesn’t have the STL container interface, it’s still a perfectly good (fixed-size) container. If it makes sense for you to use a bitset, and if you also need iterators, then you can define a simple “index iterator” adaptor that translates iterator notation like *i into array notation like b[n]. The implementation is straightforward: maintain an index and a pointer to a container.

    He does warn of his iterator:

    If we were willing to accept a slightly more cumbersome interface, we could define a class that worked with arbitrary array-like types. A general purpose index iterator adaptor is often useful when dealing with pre-STL container classes, and sometimes even when dealing with STL containers like vector.

    It should also be noted that just as with a vector<bool>::iterator, Austern's bitset_iterator::operator* doesn't return a bool& but a proxy reference: bitset<>::reference.

    Usage of bitset_iterator looks like this:

    std::bitset<10> foo;
    std::vector<bool> bar(begin(foo), end(foo));