Search code examples
c++vectorofstream

Writing a vector of vector vector structure to a binary file


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();

Solution

  • When you have nested std::vectors, 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 e.g. 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. 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);
        }  
      }
    }
    

    You may also provide a symmetrical sphere_data::load() method as well.