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

前端之家收集整理的这篇文章主要介绍了c – 运算符&=未定义的向量元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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.

原文链接:https://www.f2er.com/c/114163.html

猜你在找的C&C++相关文章