c++ - 将 std::vector<int> 保存到文件

标签 c++ serialization vector c++03

我注意到,在使用时:

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/

相关文章:

c++ - fstream 的奇怪问题。不能存储成员变量具有特定值的对象

c++ - 在头文件中声明 vector 时出错

ruby-on-rails - 编辑表单中的序列化哈希?

c++ - 在 C++ 中循环遍历字符串 vector 的字符串元素中的所有字符

c++ - 从映射中的嵌套对引用值

c++ - 为什么不能在实例化派生类指针的同时实例化对基类的引用?

c++ - 如何在 Eclipse 中创建 C++ 库?

c++ - 使用构造函数初始化 STL 映射

java - 为什么在反序列化后调用第一个构造函数而不调用其他构造函数

java - Jackson key 解串器未被调用/识别