Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning bool& from vector [duplicate]

Tags:

c++

stl

vector

In the following code:

class SomeClass {
    vector<int> i;
    vector<bool> b;

public:
    int& geti() {return i[0];}
    bool& getb() {return b[0];}
};

If you comment out getb(), the code compiles fine. Apparently there's no problem returning a reference to an int that's stored in a vector, but you can't do it with a bool.

Why is this?

like image 513
Michael Dorst Avatar asked Dec 12 '22 00:12

Michael Dorst


2 Answers

std::vector<bool> is "special." It stores its elements as a bit array, meaning that the elements are not individually addressable and you cannot obtain a reference to an element.

std::vector<bool> iterators, its operator[], and its other member functions return proxy objects that provide access to the elements without requiring actual bool objects to be stored.

If you need to be able to access individual elements, consider using a std::vector<char> or defining a bool-like enumeration backed by a char (or a signed char or unsigned char, if you care about signedness).

like image 65
James McNellis Avatar answered Dec 26 '22 10:12

James McNellis


vector<bool> is a special class template specialization for the bool type.

This specialization is provided to optimize for space allocation: eight bool elements are combined to one byte and each bool element occupies only one bit.

Reference to one bit in certain one byte is not allowed.

So the function could not return the reference to the a bool type in vector<bool>.

Someone also thinks vector<bool> is not a container.

You can use deque<bool> instead.

like image 43
konjac Avatar answered Dec 26 '22 10:12

konjac