Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

How do I store my new built data structure? C++

I have gained lots of knowledge about algorithms and data structures and how to apply them in different problems. They say: "use a binary search tree (BST) on problem X", but never what to do when the tree is constructed.

Now, for this question, I have built a BST over some objects holding some values. Also, the search function is in place. So, I compile, insert the objects, and do a search on a string. However, all this gets destroyed after the program termination and the process repeats. My intention is to keep the tree stored at some place, and be able to search in the stored BST as I want.

So, how do I keep my BST at some place and do searches on the already built tree? That is, I don't want to built the tree every time. I am planning to built a large tree that I want to have the option to search in.

Tedious example:

int main() {    
    const string s1 = "Volkswagen";
    const string s2 = "Ferrari";
    const string s3 = "Whatever";
    
    Car* g1 = new Car(s1);
    Car* g2 = new Car(s2);
    Car* g3 = new Car(s3);
    BinTree t; //construct empty tree and add to it in the following 3 lines
    t.insert(g1);
    t.insert(g2);
    t.insert(g3);
    Gene* found_gene; //declare
    found_gene = t.search("Rugbr?dsbil") //assign the found object for later use. 
}
question from:https://stackoverflow.com/questions/65922789/how-do-i-store-my-new-built-data-structure-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I'm understanding correctly you'd like to write the BST to disk and load it back up anytime the program starts?

C++ doesn't really have a built in way to do this, so you'd need to write custom logic that allows the BST to serialize and deserialize itself (to/from a string for example), and then save that data to disk (you can probably google around for disk I/O in C++), that way when the program starts up it can read the string back and recreate the tree.

https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/ here is a page I found which may help you out with specifics!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...