how to make data structures(like trees, graphs ) persistent in c++?
            Asked
            
        
        
            Active
            
        
            Viewed 1,344 times
        
    0
            
            
        - 
                    5What do you mean by 'persistant'? Do you mean writing it to disk? Keeping it alive after the function in which it was created exits? Something else? – John Dibling Mar 03 '10 at 19:59
- 
                    I would have thought it meant an immutable persistent data structure, as in the case of functional languages. – Feb 05 '18 at 05:29
3 Answers
3
            
            
        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]
 
    
    
        a'r
        
- 35,921
- 7
- 66
- 67
1
            
            
        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
 
    
    
        mentatkgs
        
- 1,541
- 1
- 13
- 17
 
     
    