将矢量矢量结构的矢量写入二进制文件
Writing a vector of vector vector structure to a binary file
std::vector<std::vector<std::vector<sphere_data> >> Sphere_image ;
我想把球体图像中的数据写入二进制文件。
谁能告诉我这是怎么做的?
我试过这个代码:
ofstream fout("C:/Project/data.dat", ios::out | ios::binary);
fout.write((char*)&Sphere_image[o], Sphere_image.size() *
sizeof(sphere_data));
fout.close();
当您嵌套std::vector
时,您在内存中不具有整个数据结构的连续性。
因此,您必须遍历所有嵌套向量"维度",并假设sphere_data
实例仅在最内层向量中具有连续性。
那么,你的行:
fout.write((char*)&Sphere_image[o], Sphere_image.size() * sizeof(sphere_data));
必须展开如下:
for (const auto& vi : Sphere_image) { // For each outer vector
for (const auto& vj : vi) { // For each sub-vector
// Now you do have contiguity for vj
fout.write(
reinterpret_cast<const char*>(vj.data()),
vj.size() * sizeof(sphere_data));
}
}
请注意,这假设sphere_data
是一个POD,因此,例如,如果你在sphere_data
内部有指针数据成员,那将不起作用。
sphere_data::save(std::ofstream& out) const
方法,您可以在最内层循环中调用该方法。sphere_data
的实例将知道如何将自己序列化为二进制文件。例如:for (const auto& vi : Sphere_image) { // For each outer vector
for (const auto& vj : vi) { // For each sub-vector
for (const auto& sd : vj) { // For each sphere data
sd.save(fout);
}
}
}
您也可以提供对称的sphere_data::load()
方法
多维向量不像多维数组那样存储在连续的内存位置。
你的向量包含
std::vector<std::vector<sphere_data>>
这只是一个向量结构本身的数组。Sphere_image.size()
给出了多维向量的顶层维度中的值的个数,仅此而已。
首先,这只会在sphere_data
是一个POD时起作用。如果它是一个类,这将不起作用。您必须分别遍历每个维度:
ofstream fout("C:/Project/data.dat", ios::out | ios::binary);
for (const auto &dim: Sphere_image)
for (const auto &dim2:dim)
fout.write(&dim2[0], dim2.size() * sizeof(sphere_data));
fout.close();
相关文章:
- 将内部带有矢量的结构保存/读取到二进制文件中
- 如何使用位字段将数据从二进制文件复制到结构中?
- 用二进制文件填充结构
- 如何在Qt中使用QDataStream将自定义结构保存/加载到二进制文件中?
- 将结构写入二进制文件后,该文件仍然具有正常字符,而不是不可读字符
- 在排序链表中插入结构并将其写入二进制文件
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 使用结构读取和写入二进制文件
- 从二进制文件中读取指向内存的二进制文件的结构
- 如何在结构中存储二进制文件数据
- C++/Python 中对象和结构的二进制文件结构
- (C++) 如何从要存储在结构数组中的二进制文件中读取.dat信息?
- 将结构保存在二进制文件中,仅在C 中读取值
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 从二进制文件中读取在结构中动态分配的数组
- 通过将结构信息从二进制文件读取到数组中,然后返回到文件C
- 用于存储数据的结构和外部二进制文件
- 将结构从二进制文件读取到链表,导致无限循环
- 加载格式化的二进制文件并将信息分配给结构 c++
- 将矢量的结构写入C 中的二进制文件