简体   繁体   English

消毒n-ary树

[英]Deserilizing n-ary tree

I'm supposed to deserialize a n-ary tree. 我应该反序列化一棵n-ary树。

this code creates my tree: 这段代码创建了我的树:

    foodtree.addChildren("Food", { "Plant", "Animal" } );
    foodtree.addChildren("Plant", { "Roots", "Leaves", "Fruits" } );
    foodtree.addChildren("Animal", { "Fish", "Mammals", "Birds" } );
    foodtree.addChildren("Roots", { "Potatoes", "Carrots" } );
    foodtree.addChildren("Leaves", { "Lettuce", "Cabbage" } );
    foodtree.addChildren("Fruits", { "Apples", "Pears", "Plums", "Oranges" } );
    foodtree.addChildren("Fish", { "Salmon", "Tuna" } );
    foodtree.addChildren("Mammals", { "Beef", "Lamb" } );
    foodtree.addChildren("Birds", { "Chicken", "Duck" } );
    foodtree.addChildren("Salmon", { "Wild", "Farm" } );
    foodtree.addChildren("Apples", { "GrannySmith", "Gala" } );

where the first argument is the parent and the second argument is a initializer list that is the children of the first argument. 其中第一个参数是父参数,第二个参数是初始化列表,它是第一个参数的子元素。

my serialize function looks like this: (I'm using 2 functions to do this) 我的序列化函数看起来像这样:(我用2个函数来做这个)

template<typename T>
void Ntree<T>:: serializeHelper (node* r, ofstream& ofs) 
{
    if(r->child.size() > 0)
        ofs<<r->val <<"     ";

    for(int i=0; i < r->child.size(); i++)
        ofs<<r->child[i]->val <<" ";

    if(r->child.size() > 0) 
    ofs << "\n";

    vector<node*> vt = r->child;

    for (int j = 0; j < vt.size(); j++) 
        serializeHelper(vt[j], ofs);

}


template <typename T>
void Ntree<T>::serialize(std::string filename)
{
    ofstream ofs(filename);
    serializeHelper(root, ofs);
}

After calling foodtree.serialize("foodtree.out"). 在调用foodtree.serialize(“foodtree.out”)之后。 My .OUT file looks like this: 我的.OUT文件如下所示:

Food     Plant Animal 
Plant     Roots Leaves Fruits 
Roots     Potatoes Carrots 
Leaves     Lettuce Cabbage 
Fruits     Apples Pears Plums Oranges 
Apples     GrannySmith Gala 
Animal     Fish Mammals Birds 
Fish     Salmon Tuna 
Salmon     Wild Farm 
Mammals     Beef Lamb 
Birds     Chicken Duck 

I wish to write a deserialize function which will take this file in and create a n-ary tree. 我希望编写一个反序列化函数,它将获取此文件并创建一个n-ary树。 The in each line, first word in the .OUT file has to be the parent node and the following words have to be the children. 在每行中,.OUT文件中的第一个单词必须是父节点,以下单词必须是子节点。 I don't know how I should go about this. 我不知道应该怎么做。 Any help is appreciated. 任何帮助表示赞赏。

All I have so far is: void Ntree::deserialize(string& filename); 到目前为止,我只有:void Ntree :: deserialize(string&filename); :P :P

Think of it this way. 这样想吧。

How did you create the tree in the first place? 你是如何创建树的?

Do the same, except instead of using literal values get the values from the file. 执行相同操作,但不使用文字值从文件中获取值。 Also use a loop instead of separate addChildren statements. 也可以使用循环而不是单独的addChildren语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM