简体   繁体   中英

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?

If you do not want to write loops using the operator[] of the bitset , then you might try using bitset::to_string() to convert the bitset to a string of '1' and '0' . Since C++11, you can actually choose different characters than those two, so you could actually choose '\\0' and '\\1' .

Are you sure bitset is the optimal type for your task?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM