我用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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。