Reputation: 4244
how to make data structures(like trees, graphs ) persistent in c++?
Upvotes: 0
Views: 1417
Reputation: 1601
struct S {
/* ... */
};
//...
ofstream out("temp.aux");
S s;
char* c = reinterpret_cast<char*>(&s);
out << sizeof(s);
for(int i = 0; i < sizeof(s); ++i) {
out << c[i];
}
out.close();
// ...
ifstream in("temp.aux");
int size;
in >> size;
char* r = new char[size];
for(int i = 0; i < size; ++i) {
in >> r[i];
}
S* s = reinterpret_cast<S*>(r);
in.close();
quick and dirty =D
Upvotes: 1
Reputation: 140182
Try Google Protocol Buffers or the Boost serialization library.
Upvotes: 5
Reputation: 37029
In general, you will need to serialise the structure so that you can write it to a file or a database. If you have a custom structure, then you will need to write the method to serialise and deserialise (i.e. write out and read in the structure). Otherwise, if you have used a structure from a library, there may already be (de)serialisation methods.
eg. A linked list might serialise as a string like so: [1,2,3,4,5]
Upvotes: 3