vector<bool> push_back

This is a discussion on vector<bool> push_back within the C++ Programming forums, part of the General Programming Boards category; I have a piece of code which converts a string into a vector<bool>. To do that, I have to use ...

vector<bool> push_back

I have a piece of code which converts a string into a vector<bool>. To do that, I have to use push_back() 8 times for every byte, and it can get into millions of bytes. Is there a way I can speed this up?

//edit: Also, how are bool's represented in memory? Can I do a union between chars and bools and do it that way?

For Boolean elements of a vector, the C++ standard library provides a specialization of vector. The goal is to have a version that is optimized to use less size than a usual implementation of vector for type bool. Such a usual implementation would reserve at least 1 byte for each element. The vector<bool> specialization usually uses internally only 1 bit for an element, so it is typically eight times smaller. Note that such an optimization also has a snag: In C++, the smallest addressable value must have a size of at least 1 byte. Thus, such a specialization of a vector needs special handling for references and iterators.

As a result, a vector<bool> does not meet all requirements of other vectors (for example, a vector<bool>::reference is not a true lvalue and vector<bool>::iterator is not a random access iterator). Therefore, template code might work for vectors of any type except bool. In addition, vector<bool> might perform slower than normal implementations because element operations have to be transformed into bit operations. However, how vector<bool> is implemented is implementation specific. Thus, the performance (speed and memory) might differ.

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens