c++pointersvectorboolean

Create a pointer to an element in a vector<vector<bool>>


If I want a pointer to an element in a vector of vectors of int, I write:

vector<vector<int>> a (5);
int* p1 = a[4].data();

However, it doesn't work with a vector of vectors of bool (why?) when I write:

vector<vector<bool>> b(5);
bool* p2 = b[4].data();

The compiler outputs the following error message:

Semantic issue: Error: Cannot initialize a variable of type "bool*" with an rvalue of type "void".

Solution

  • std::vector<bool> unfortunately is a specialization that may save space by using just a bit for each element. This is not guaranteed but can happen.

    When this happens it means that using pointers to element is not possible (the minimum size of an object in C++ is one byte) and also a lot of other specifics of std::vector do not work for std::vector<bool>.

    Just don't use it... if you need bit packing implement it yourself (at least you know what you get in a portable way) and if you don't care about the bit vs byte saving just use an std::vector<unsigned char> instead (that is a real std::vector).

    std::vector<bool> specialization was basically a mistake of C++, it has no meaningful use. Doesn't provide any guaranteed advantage and may create problems in the future (for example even for code that currently doesn't need proper standard iterators now, may be the code will need to evolve into needing them, and if you used vector<bool> then you're doomed).