The & = operator for <bool> vector elements is not defined?

I did some tests with operator &= . As the following examples show, this works for one type of bool , as well as a type of vector<int> , but not vector<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; } 

Can anyone tell what is going on here?

(I am using gcc 4.4.3)

+6
source share
2 answers

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

The article says:

(If someone else wrote a vector, it would be called β€œnon-compliant” and β€œnon-standard.” Well, it's in the standard, so it's a little harder to name these names at the moment, but some in any case, we hope that it’s in will be cleared eventually. The correct solution is to remove the vector specialization requirement for the vector to really be a vector of plain old bools. Furthermore, it is basically redundant: std :: bitset was designed for this kind of thing.) ....

The reason std :: vector is inappropriate is that it pulls tricks under covers in an attempt to optimize the space : instead of storing a full char or int for each bool (taking at least 8 times in space, on platforms with 8-bit characters), it packs bools and saves them as separate bits (inside, say, characters) in the internal representation . One consequence of this is that it cannot simply return the normal bool & from its operator [] or its dereferenced iterators [2]; instead, it should play games with a proxy helper class that is similar to bool, but definitely not bool. Unfortunately, this also means that access to the vector is slower because we have to deal with proxies instead of direct pointers and links.

+8
source

The reason for this is that vector<bool > is explicitly called in the standard to accept only one bit per element.

The result of this is that operator[] for vector<bool> returns a proxy object instead of a direct link, like any other contained type. Then the proxy object does not support operator&= (again, most likely, for each standard, although I have no link).

You can use deque<bool> if you want to use a byte for each element and work as an operator as expected.

+5
source

Source: https://habr.com/ru/post/886905/


All Articles