I write tools to dump and load common objects in a binary file. In a first quick implementation, I wrote the following code for std::vector<bool>
. It works, but it is clearly not optimized in memory.
template <>
void binary_write(std::ofstream& fout, const std::vector<bool>& x)
{
std::size_t n = x.size();
fout.write((const char*)&n, sizeof(std::size_t));
for(std::size_t i = 0; i < n; ++i)
{
bool xati = x.at(i);
binary_write(fout, xati);
}
}
template <>
void binary_read(std::ifstream& fin, std::vector<bool>& x)
{
std::size_t n;
fin.read((char*)&n, sizeof(std::size_t));
x.resize(n);
for(std::size_t i = 0; i < n; ++i)
{
bool xati;
binary_read(fin, xati);
x.at(i) = xati;
}
}
How can I copy the internal memory of a std::vector<bool>
in my stream ?
Note : I don't want to replace std::vector<bool>
by something other.
std::vector<bool>
elsewhere in the code, I strongly suggest you move to something likestd::bitset
orboost::dynamic_bitset
and use theirto_string
functionality, or theirostream
overloads ofoperator<<
. – Antipodesto_string
for a binary storage ? Really ? ^^ – Deficiencystd::vector<bool>
(see e.g. this question) – Antipodes