开发者

memory layout of vector<bool>

开发者 https://www.devze.com 2023-01-24 02:14 出处:网络
Can someone please explain the memory layout of the data stored in a vector<bool>? like what layout does the memory have from address &myVec[0] upwards? Does it depend on endianness? Is the

Can someone please explain the memory layout of the data stored in a vector<bool>?

like what layout does the memory have from address &myVec[0] upwards? Does it depend on endianness? Is the memory continguous for all stored values? (i'm aware that vector<bool> doesn't actually store booleans). can I dump the content of a v开发者_JS百科ector<bool> into a file using memcopy to get a bitmap of my values?

please no questions like "what do you need it for" or suggestions like using bitsets or boost.

Thank you for an accurate explanation


The std::vector will simply manage a raw array on the heap. So whan you do &myVec[0] you get the address of the first element of this array. As it's an array it...follows the rules of a raw array..

BUT

std::vector is a special case, a specific implementation, a mistake of the C++ commitee that is NOT a vector of bool but a container managing bits. So avoid using this one.


A vector is essentially a wrapper around an array so yes, the memory is contiguous. This also means you can use memcpy on it (if that's what you want).

The endianness of each element depends on your current architecture.

vector<bool> myvector;
myvector.push_back(1);
myvector.push_back(0);
myvector.push_back(0);
myvector.push_back(1);
myvector.push_back(0);
myvector.push_back(1);
myvector.push_back(1);
myvector.push_back(0);

would appear like this in memory:

1 0 0 1 0 1 1 0

I'm not sure if that is what you are asking.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号