Return bool & from 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 in order. There seems to be no problem returning an int reference that is stored in a vector, but you cannot do this with bool .

Why is this?

+4
source share
2 answers

std::vector<bool> is "special." It saves its elements as a bitmap, which means that the elements are not individually addressed, and you cannot get a link to the element.

Iterators

std::vector<bool> , its operator[] and its other member functions return proxy objects that provide access to elements without requiring the storage of real bool objects.

If you need to have access to individual elements, consider using std::vector<char> or defining bool numbering supported by char (or signed char or unsigned char if you're interested in character).

+11
source

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

This specialization is provided to optimize the distribution of space: eight bool elements are combined into one byte, and each bool element occupies only one bit.

Reference to one bit in a specific byte is not allowed.

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

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

You can use deque < bool > instead.

+2
source

All Articles