Is there a standard way (or at least semi-standard, implemented in all popular compilers) to get a non-specialized, non-optimized, contiguous std::vector<bool>
container?
I have some generic code dealing with std::vector
s which assumes they are all such standard, contiguous containers. My current workaround is to use a std::vector<int>
which just stores 0's and 1's, which is what I want content-wise, but it would be nicer to have the correct vector type.
First, what's wrong with vector<bool> ? Because vector<bool> holds bits instead of bools, it can't return a bool& from its indexing operator or iterator dereference. This can play havoc on quite innocent looking generic code.
The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocatorallocatorAllocators are used by the C++ Standard Library to handle the allocation and deallocation of elements stored in containers. All C++ Standard Library containers except std::array have a template parameter of type allocator<Type> , where Type represents the type of the container element.https://learn.microsoft.com › cpp › standard-library › allocatorsAllocators - Microsoft Learn for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.
Element i of the vector created by vector1 == vector2 equals TRUE if vector1[i] == vector2[i] and equals FALSE otherwise. A vector in which every element is TRUE or FALSE is called a Boolean vector.
As workaround you might use other type, char
comes in mind.
Else you can write a wrapper around bool
, something like:
struct my_bool
{
operator bool() const { return b; }
operator bool&() { return b; }
bool b;
};
Generally, use of std::vector<bool>
specialization is not consider a good practice, with exceptions of-course. Mainly, because its interface is different with that of the primary std::vector<T>
and this causes a lot of confusion.
This irregularity, is mentioned in several publications that are loose in the web. A recent one and IMHO a good read is written by Howard Hinnant namely On vector<bool>
.
In fact sometime ago there was a proposal to remove it from from the standard N1185, but it was rejected for backward compatibility issues.
Most proposed semi-standard alternative is the use of std::vector<unsigned char>
or std::vector<char>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With