简体   繁体   English

我可以得到一个非专业的矢量 <bool> 输入C ++?

[英]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> . vector<bool>专门用于减少空间消耗(每个元素1位),但访问速度比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. 有时我出于性能原因使用vector<char> ,但是如果我将char转换为bool ,我的编译器(Visual C ++)可能会生成一个我不喜欢的C4800警告。

Also, I think the vector<char> is semantically wrong if I treat it as unspecialized vector<bool> . 另外,我认为如果我把它视为非专用vector<bool> ,那么vector<char>在语义上是错误的。 So, can I get a real unspecialized vector<bool> type in C++? 那么,我可以在C ++中获得一个真正的非专业化vector<bool>类型吗?

No you can't get an unspecialized std::vector<bool> . 不,你不能得到一个非专业的std::vector<bool>

vector<char> is your best bet as you already figured out. 你已经想通了, vector<char>是你最好的选择。 To get around the warning, just use a bool expression: 要绕过警告,只需使用bool表达式:

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

Alternatively, create a custom bool class: 或者,创建一个自定义bool类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM