简体   繁体   中英

C++ save vector of vector of vector of class object into file

I have a class in c++ like the following:

class myCls
{
public:
   myCls();
   void setAngle(float angle);
   void setArr(unsigned char arr[64]);    
   unsigned char arr[64];
   double angle;
   int index;

   static float calcMean(const unsigned char arr[64]);
   static float sqrt7(float x);

};

Now in my main program I have a 3D vector of the class:

vector<vector<vector< myCls > > > obj;

The size of the vector is also dynamically changed. My question is that how can I store the content of my vector into a file and retrieve it afterward?

I have tried many ways with no success.This is my try:

std::ofstream outFile;
outFile.open(fileName, ios::out);
for(int i=0;i<obj.size();i++)
    {
        outFile.write((const char *)(obj.data()),sizeof(vector<vector<myCls> >)*obj.size());
    }
outFile.close();

And for reading it:

vector<vector<vector<myCls>>> myObj;
id(inFile.is_open())
{
    inFile.read((char*)(myObj.data()),sizeof(vector<vector<myCls> >)*obj.size());
}

What I get is only runTime error.

Can anyone help me in this issue please?

If you don't care too much about performance, try boost::serialization . Since they've already implemented serialization functions for stl containers, you would only have to write the serialize function for a myCL , and everything else comes for free. Since your member variables are all public, you can do that intrusively or non-intrusively .

Internally, a vector most usually consists of two numbers, representing the current length and the allocated length (capacity), as well as a pointer to the actual data. So the size of the “raw” object is fixed and approximately thrice the size of a pointer. This is what your code currently writes. The values the pointer points at won't be stored. When you read things back, you're setting the pointer to something which in most cases won't even be allocated memory, thus the runtime error.

In general, it's a really bad idea to directly manipulate the memory of any class which provides constructors, destructors or assignment operators. Your code writing to the private members of the vector would thoroughly confuse memory management, even if you took care to restore the pointed-at data as well. For this reason, you should only write simple ( POD ) data the way you did. Everything else should be customized to use custom code.

In the case of a vector, you'd probably store the length first, and then write the elements one at a time. For reading, you'd read the length, probably reserve memory accordingly, and then read elements one at a time. The boost::serialization templates suggested by Voltron will probably save you the trouble of implementing all that.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM