9

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

EFanZh
  • 2,357
  • 3
  • 30
  • 63
  • Unfortunately, not from the standard library. Try `deque`, or `boost::container::vector`? – T.C. Jan 11 '15 at 04:23
  • 1
    You may want to tell us *how* you're converting a `char` to a `bool` if it's giving you a warning. The link you provided shows how to avoid that warning. – Drew Dormann Jan 11 '15 at 04:25
  • @DrewDormann When I return a `vector`'s element in a function that returns `bool`. But I don't think it's important, because a `char` shouldn't be treat as a `bool`, although it can. – EFanZh Jan 11 '15 at 04:29
  • you could always create a class `Bool` that mirrors the functionality of `bool`, and have a `vector` of that. – sp2danny Jan 11 '15 at 06:35
  • @sp2danny: Sure, but note that `sizeof(Bool)` might not be equal to `sizeof(bool)`. – MSalters Jan 11 '15 at 07:04

1 Answers1

4

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];
Rado
  • 8,634
  • 7
  • 31
  • 44