Can I get a non-specialized vector <bool> in C ++?

A vector<bool> specialized to reduce space consumption (1 bit for each element), but it is slower to access than vector<char> . Sometimes I use vector<char> to improve performance, but if I convert char to bool , my compiler (Visual C ++) can generate a C4800 warning which I don't like.

In addition, I think that vector<char> is semantically incorrect when viewed as a non-specialized vector<bool> . So, can I get a real non-specialized type of vector<bool> in C ++?

+7
c ++ template-specialization
source share
1 answer

No, you cannot get the non-specialized std::vector<bool> .

vector<char> is your best bet, as you've already figured out. To get around the warning, just use the bool expression:

 bool b1 = v[0] != 0; bool b2 = !!v[0]; 

Alternatively, create your own 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]; 
+3
source share

All Articles