A vector<bool>
is specialized to reduce space consumption (1 bit for each element), but it's slower to access than vector<char>
. Sometimes I use a vector<char>
for performance reason, but if I convert a char
to a bool
, my compiler (Visual C++) may generate a C4800 warning which I don't like.
Also, I think the vector<char>
is semantically wrong if I treat it as unspecialized vector<bool>
. So, can I get a real unspecialized vector<bool>
type in C++?
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 allocator for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.
No you can't get an unspecialized std::vector<bool>
.
vector<char>
is your best bet as you already figured out. To get around the warning, just use a bool expression:
bool b1 = v[0] != 0;
bool b2 = !!v[0];
Alternatively, create a custom bool class:
class Bool
{
public:
Bool(){}
Bool(const bool& val) : val_(val) {}
inline Bool& operator=(const bool& val) { val_ = val; }
operator bool() const { return val_; }
private:
bool val_;
};
...
vector<Bool> bvec;
bvec.push_back(false);
bvec.push_back(true);
bool bf = bvec[0];
bool bt = bvec[1];
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