将矢量矢量结构的矢量写入二进制文件

Writing a vector of vector vector structure to a binary file

本文关键字:二进制文件 结构      更新时间:2023-10-16
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();