我注意到,在使用时:
std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ios::out | std::ofstream::binary);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile));
outfile.close();
我的 std::vector<int>
未序列化为原始字节数据(每个 int
4 个字节),而是序列化为字符串,即将每个整数的字符串表示形式保存到磁盘,这是我不想要的。
如何保存 std::vector<int>
作为二进制数据?
(注意:在学习它的新方法之前,我想用标准 C++03 来学习它)。
最佳答案
要写入二进制数据,请使用 std::ostream::write()
而不是 std::ostream_iterator
(内部使用 operator<<
,因此格式化输出),例如:
std::vector<int> v(100000);
...
std::ofstream outfile("outfile.dat", std::ofstream::binary);
outfile.write(reinterpret_cast<const char*>(v.data() /* or &v[0] pre-C++11 */), sizeof(int) * v.size());
outfile.close();
关于c++ - 将 std::vector<int> 保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643889/