I've a class (Database) which have a variable std::vector<short>, simply.
I only push_back four values (-1, 0, 1, 2) in my code.
Everything works, but if I save in an bin file, then exit the program and
re-open it, and finally load, the program crashes when I do the same lines : the push_back.
I save with this line :
file.write( reinterpret_cast<char*>(&map[x][y]), sizeof(cell) );
I load like this :
file.read( reinterpret_cast<char*>(&map[x][y]), sizeof(cell) );
An exemple line of the push_back is :
map[bufRet[i].x][bufRet[i].y].data3.push_back(-1);
Who 'map' is a class object (cell), 'bufRet' a vector, i is between 0 and bufRet.size()-1 included, 'bufRet[i].x' and 'bufRet[i].y' aren't out of range, 'data3' is the vector<short> in question (no pointer or reference).
You can't write vectors to file like that. A vector contains a pointer to where the elements are stored so only the pointer will be written to the file.
A better way is to loop through each vector and write each element one by one. You probably also want to write the size of the vectors so that you know how many elements you should read when you later restore the map from the file.
oh I see, so I have to write the size of the vector, run through the loop for the vector and write each element, and reverse this procedure for read if I've understood.
I go to test this method and I come back for tell if it's a good solution, thanks my man !
Edit : ok it works fine. Thanks Peter87, now I understand better how works the std::vector.