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();
答案 0 :(得分:2)
多维向量不存储在连续的存储位置,就像多维数组一样。
你的矢量包含
std::vector<std::vector<sphere_data>>
这只是一个矢量结构本身的数组。 Sphere_image.size()
为您提供多维向量的顶级维度中的值的数量,这就是全部。
首先,这仅适用于sphere_data
is a 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();
答案 1 :(得分:2)
当您嵌套std::vector
时,您的内存中没有整个数据结构的连续性。
因此,您必须遍历所有嵌套向量&#34;维度&#34; ,并假设{em>最内层中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
的实例将知道如何将自己序列化为二进制文件。 E.g:
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()
方法。