简体   繁体   中英

Can I get an unspecialized vector<bool> type in C++?

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++?

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

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