【发布时间】:2016-10-07 04:19:11
【问题描述】:
真的很奇怪,我在stackoverflow上没有找到这个问题的答案。
我想将std::vector<int> 保存到文件中。
在不同的地方我发现了以下代码:
std::vector<int> v{0,1,2,4,8,16,32,64,128,256,512};
std::ofstream outfile("test.data", std::ios::out | std::ofstream::binary);
std::copy(v.begin(), v.end(), std::ostreambuf_iterator<char>(outfile));
outfile.close();
但这里的问题是,std::ostreambuf_iterator<char> 在将v 的每个值写入文件之前将其转换为char。因此值256 和512 更改为0。生成的文件在 hexedit 下如下所示:
00000000 00 01 02 04 08 10 20 40 80 00 00
我的想法是将std::ostreambuf_iterator<char> 更改为std::ostreambuf_iterator<int>,但这不起作用。编译器抛出错误:
error: no matching function for call to ‘std::ostreambuf_iterator<int>::ostreambuf_iterator(std::ofstream&)’
std::copy(v.begin(), v.end(), std::ostreambuf_iterator<int>(outfile));
我该如何解决这个问题?
【问题讨论】:
-
#include <ostream>和#include <iterator>。也可能是#include <fstream> -
@Arunmu 两者都包括在内。
-
只需删除
| std::ofstream::binary。反正你也不想要二进制文件。 -
std::ostreambuf_iterator要求模板参数为 char 类型。您可以尝试使用wchar,但对于大于65535 的值仍然会失败。为什么不使用<<运算符将向量写入文件流? -
@Alf 值仍在转换为整数。
标签: c++ c++11 serialization save