Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialise/deserialise a std::vector<bool> most efficiently?

Tags:

c++

c++11

stl

I'm trying to write the contents of a std::vector<bool> to disk into a binary file. As the write() method of many of the STL output streams takes in a pointer to the array itself, as well as the number of bytes to write, for a 'normal' vector I'd end up doing something like this:

std::vector<unsigned int> dataVector = {0, 1, 2, 3, 4};
std::fstream outStream = std::fstream("vectordump.bin", std::ios::out | std::ios::binary);
outStream.write((char*) dataVector.data(), dataVector.size() * sizeof(unsigned int));
outStream.close();

However, the std::vector<bool> is a special case, as the STL implementation is allowed to pack the bools into single bits. The above approach will therefore technically not consistently work, because it's unspecified how the data is precisely laid out in memory.

Is there any way of serialising/deserialising my bool vector without having to pack/unpack the data?

like image 788
Bartvbl Avatar asked Dec 14 '22 09:12

Bartvbl


2 Answers

I think you're better off to just translate that vector into std::vector<std::byte>/std::vector<unsigned char>.

std::vector<bool> isn't even required to have contiguous memory so writing starting from data() is implementation defined too.

like image 164
Hatted Rooster Avatar answered Mar 16 '23 00:03

Hatted Rooster


No, there isn't.

Sorry.

A good reason to avoid this container!

like image 40
Lightness Races in Orbit Avatar answered Mar 15 '23 23:03

Lightness Races in Orbit