【发布时间】:2015-04-14 09:19:52
【问题描述】:
我编写工具来转储和加载二进制文件中的常见对象。在第一个快速实现中,我为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> 其他东西。
【问题讨论】:
-
即使你已经在代码的其他地方使用了
std::vector<bool>,我强烈建议你改用std::bitset或boost::dynamic_bitset并使用他们的to_string功能,或者他们的ostreamoperator<<的重载。 -
to_string用于二进制存储?真的吗 ? ^^ -
对,这不是我最聪明的评论;)。尽管如此,在查找 std::bitset 的功能之后,这似乎是唯一的方法(bitset->string->某种整数)。那,或者一个一个地获取位。我很好奇哪个会更快......嗯,再想一想,坚持
std::vector<bool>(参见例如this question) -
使数据持久化是序列化程序的工作。不需要手工制作。
-
@Klaus:编写一个有特定需求的序列化程序是我的工作。我不需要判断问题的相关性。我需要解决方案。 ;-)