加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 运算符&=未定义的向量元素?

发布时间:2020-12-16 05:39:17 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why vectorbool::reference doesn’t return reference to bool?6个 我用operator =做了一些测试.如下面的示例所示,这适用于单个bool类型以及向量 int类型,但不是矢量 bool. #include vectorint main (){ bool a,b; a = b; // ok std::vectorbo
参见英文答案 > Why vector<bool>::reference doesn’t return reference to bool?6个
我用operator& =做了一些测试.如下面的示例所示,这适用于单个bool类型以及向量< int>类型,但不是矢量< bool>.
#include <vector>
int main (){

    bool a,b;
    a &= b; // ok
    std::vector<bool> c(1);
    c[0] &= b; // error
    c[0] = c[0] & b; // ok
    std::vector<int> d(1);
    d[0] &= b; // ok

    return 0;
}

谁能告诉我们这里发生了什么?

(我正在使用gcc 4.4.3)

解决方法

vector<bool> is not a container actually .:P

文章说

(If anyone else had written vector,it would have been called “nonconforming” and “nonstandard.” Well,it’s in the standard,so that makes it a little bit harder to call it those names at this point,but some of us try anyway in the hopes that it will eventually get cleaned up. The correct solution is to remove the vector specialization requirement so that vector really is a vector of plain old bools. Besides,it’s mostly redundant: std::bitset was designed for this kind of thing.)
….

The reason std::vector is nonconforming is that it pulls tricks under the covers in an attempt to optimize for space: Instead of storing a full char or int for every bool (taking up at least 8 times the space,on platforms with 8-bit chars),it packs the bools and stores them as individual bits (inside,say,chars) in its internal representation. One consequence of this is that it can’t just return a normal bool& from its operator[] or its dereferenced iterators[2]; instead,it has to play games with a helper “proxy” class that is bool-like but is definitely not a bool. Unfortunately,that also means that access into a vector is slower,because we have to deal with proxies instead of direct pointers and references.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读