Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator &= for elements of vector<bool> not defined? [duplicate]

Tags:

c++

I did some tests with the operator &=. As the following examples shows, this works for single bool type as well as a vector<int> type, 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'm using gcc 4.4.3)

like image 743
kunigami Avatar asked Apr 28 '11 17:04

kunigami


People also ask

What is an operator and operand?

An operand can be a constant, a variable or a function result. Operators are arithmetic, logical, and relational. As with C, some operators vary in functionality according to the data type of the operands specified in the expression.

What is the main function of operator?

An operator is used to manipulate individual data items and return a result. These items are called operands or arguments. Operators are represented by special characters or by keywords.

What is the meaning of operator in business?

operator noun [C] (PERSON OR BUSINESS)someone who is skilled at dealing with people and getting what he or she wants from a situation: He has shown himself to be a canny operator in wage negotiations. More examples. We rationalized the production system so that one operator could control all three machines.


1 Answers

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

The article says

(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.

like image 63
Prasoon Saurav Avatar answered Sep 21 '22 00:09

Prasoon Saurav