gpt4 book ai didi

c++ - 如何在二进制文件中转储 std::vector

转载 作者:行者123 更新时间:2023-12-04 13:11:21 27 4
gpt4 key购买 nike

我编写工具来转储和加载二进制文件中的常见对象。在第一个快速实现中,我为 std::vector<bool> 编写了以下代码.它有效,但显然没有在内存中进行优化。

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;
}
}

如何复制 std::vector<bool> 的内部存储器在我的流中?

注意:我不想换 std::vector<bool>通过别的东西。

最佳答案

回答我自己的问题 ,目前被验证为最佳答案,但如果有人提供更好的东西,它可能会改变。

一种方法如下。它需要访问每个值,但它有效。

template <>
void binary_write(std::ofstream& fout, const std::vector<bool>& x)
{
std::vector<bool>::size_type n = x.size();
fout.write((const char*)&n, sizeof(std::vector<bool>::size_type));
for(std::vector<bool>::size_type i = 0; i < n;)
{
unsigned char aggr = 0;
for(unsigned char mask = 1; mask > 0 && i < n; ++i, mask <<= 1)
if(x.at(i))
aggr |= mask;
fout.write((const char*)&aggr, sizeof(unsigned char));
}
}

template <>
void binary_read(std::ifstream& fin, std::vector<bool>& x)
{
std::vector<bool>::size_type n;
fin.read((char*)&n, sizeof(std::vector<bool>::size_type));
x.resize(n);
for(std::vector<bool>::size_type i = 0; i < n;)
{
unsigned char aggr;
fin.read((char*)&aggr, sizeof(unsigned char));
for(unsigned char mask = 1; mask > 0 && i < n; ++i, mask <<= 1)
x.at(i) = aggr & mask;
}
}

关于c++ - 如何在二进制文件中转储 std::vector<bool> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29623605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com