2016-12-30 1 views
1

私が書いているコードで助けが必要です。私のアイデアは、(私は参照で渡すルートは、与えられたルートに子ノードを計算する再帰関数を呼び出すことですが、再帰関数が終了すると、子は格納されません。私が間違っていることを誰かが教えてくれたら、私はそれを感謝します。コードは次のとおりです。ツリー再帰C++関数終了後の子ノードの値が欠落しています

struct TreeNode 
{ 
    string label; 
    TreeNode* parent; 
    vector<TreeNode*> children; 
    string value; 
}; 

void id3(vector<string> attributes, vector<int> attributes_sizes, vector<Data> set, TreeNode &root) 
{ 
    // .. some other code goes here 

    for(int i = 0; i < current_attribute_size; i++) 
    { 
     if(final_entropy[i].second == 0.0 && final_result[i].second.size() > 0) 
     { 
      TreeNode child; 
      child.label = final_result[i].first; 
      child.parent = &root; 
      root.children.push_back(&child); 
      child.value = final_result[i].second[0].node_caps; 
     } 
     else if(final_result[i].second.size() > 0 && attributes.size() > 0) 
     { 
      TreeNode child; 
      child.label = final_result[i].first; 
      child.parent = &root; 
      root.children.push_back(&child); 
      id3(attributes, attributes_sizes, final_result[i].second, child); 
     } 
    } 
    return; 
} 

int main() 
{ 
    // .. some other code goes here for the other arguments passed to id3 

    TreeNode root; 
    id3(attributes, attributes_sizes, educational, root); 

    return 0; 
} 

他の機能は問題ではないと私は考えていません。私もコピーしません。

答えて

1

TreeNode構造体を詳しく知らなくても、私はあなたが参照としてpush_back &childを参照し、childがローカル/一時変数であることが問題だと思います。

私はあなたが書くべきとします

TreeNode *child = new TreeNode(); 
child->label = ... 
root.children.push_back(child); 
+0

はどうもありがとうございました!私はTreeNodeクラスを追加するのを忘れました、はい、それは今うまくいくようです!再度、感謝します! :) – vixenn

関連する問題