std::vector<std::vector<std::vector<sphere_data> >> Sphere_image ;
I want to write the data in sphere image to binary file.
Could any one tell me how can this be done.
I tried this Code:
ofstream fout("C:/Project/data.dat", ios::out | ios::binary);
fout.write((char*)&Sphere_image[o], Sphere_image.size() *
sizeof(sphere_data));
fout.close();
A multi-dimensional vector is not stored in consecutive memory locations, like a multi-dimensional array is.
Your vector contains a
std::vector<std::vector<sphere_data>>
This is just an array of vector structures themselves. Sphere_image.size()
gives you the number of values in the top level dimension of the multi-dimensional vector, that's all.
First of all, this will only work if sphere_data
is a POD . If it is a class, this will not work. You have to iterate over each dimension separately:
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();
When you have nested std::vector
s, you don't have contiguity in memory for the whole data structure.
So, you have to iterate through all the nested vectors "dimensions" , and assume contiguity of sphere_data
instances only in the innermost vector.
So, your line:
fout.write((char*)&Sphere_image[o], Sphere_image.size() * sizeof(sphere_data));
must be expanded something like that:
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));
}
}
Note that this assumes that sphere_data
is a POD , so eg if you have pointer data members inside sphere_data
, that won't work.
In this case, you may provide a sphere_data::save(std::ofstream& out) const
method, which you can call in the innermost loop. Instances of sphere_data
will know how to serialize themselves to binary files. Eg:
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);
}
}
}
You may also provide a symmetrical sphere_data::load()
method as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.