I'm using memcpy to copy the content of std:vectors<> to primitve Arrays. For datatypes like int, float, double etc. it worked well. As I started to copy a boolvector I encountered a problem namely I got strange values.
First I started to make an test output for a float vector:
std::vector<float> test1 (3,0);
cout << "Sizeof test1[0] : " << sizeof(test1[0]) << endl
<< "Memoryaddress 0: " << &test1[0] << endl
<< "Memoryaddress 1: " << &test1[1] << endl
<< "Memoryaddress 2: " << &test1[2] << endl;
The output is:
Sizeof test1[0]: 4
Memoryaddress 0: 02793820
Memoryaddress 1: 02793824
Memoryaddress 2: 02793828
And this is what I expect. The float size is 4 Byte and the distance to the next float value is 4 Byte. When I do this for bool the output looks like this:
std::vector<bool> test (3,0);
cout << "Sizeof test[0]: " << sizeof(test[0]) << endl
<< "Memoryaddress 0: " << &test[0] << endl
<< "Memoryaddress 1: " << &test[1] << endl
<< "Memoryaddress 2: " << &test[2] << endl;
The output is:
Sizeof test[0]: 16
Memoryaddress 0: 011EF94C
Memoryaddress 1: 011EF93C
Memoryaddress 2: 011EF92C
Why is the size of bool 16 Byte? It seems like a total overkill to me. Are there explanations for this?
Unlike other specialisations of vector
, vector<bool>
does not manage a dynamic array of bool
objects. Instead, it is supposed to pack the boolean values into a single bit each.
Since individual bits are not addressable, test[0]
cannot simply be a reference to bool
. Instead, it is an class type vector<bool>::reference
that can be converted to bool
(to get the value), and assigned from bool
(to modify the vector element).
This means that vector<bool>
doesn't entirely meet the requirements of a standard container, and can't be used if you need references or pointers to its elements. If you do require a "real" container with addressable elements, consider vector<char>
or deque<bool>
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With