how to make data structures persistent in c++?

倖福魔咒の 提交于 2020-01-06 07:14:40

问题


how to make data structures(like trees, graphs ) persistent in c++?


回答1:


Try Google Protocol Buffers or the Boost serialization library.




回答2:


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]




回答3:


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



来源:https://stackoverflow.com/questions/2374066/how-to-make-data-structures-persistent-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!