Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 345
EFanZh Avatar asked Jan 11 '15 04:01

EFanZh


People also ask

Why not to use vector bool?

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.

What is vector bool in c?

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.


1 Answers

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];
like image 60
Rado Avatar answered Sep 18 '22 20:09

Rado