2017-10-17 192 views
-1

爲節點實現了一個C++類,但以某種方式在刪除節點時仍然出現錯誤。C++將已刪除節點的子節點移到樹中的父節點

一般algorithim是這樣的:

  • 設定孩子的PARENT_到PARENT_
  • 孩子添加到父
  • 的孩子從這個節點
  • 的孩子取出孩子

這裏是我的類文件:

template <typename E> 
class TNode{ 

    ... 

bool remove(){ 
      if ((parent_==NULL) && (children_.size()>0)){ 
       cout << "can't remove the root if it has children\n"; 
       return false; 
      } 
      else{ 

       parent_->children_.erase(std::remove(parent_->children_.begin(), parent_->children_.end(), this), parent_->children_.end()); 

       for (int i=children_.size()-1;i>=0; i--){ 

        //my error is happening here 

        parent_ = parent_ -> children_; 
        this = children_ -> this; 
        parent_ = parent_ -> this; 
       } 

       //delete (deallocate memory of) this node 
       delete this; 
       return true; 
      } 
     } 

     friend class gTree<E>; 

     private: 
     E data_; 
     gTNode<E>* parent_; 
     std::vector<gTNode<E>*> children_; 
    }; 

有人能指引我正確的方向嗎?

編輯的錯誤是這樣的:

gTree.h: In member function ‘bool gTNode<E>::remove()’: 
gTree.h:50:29: error: expected unqualified-id before ‘this’ 
     this = children_ -> this; 
          ^
gTree.h:50:29: error: expected ‘;’ before ‘this’ 
gTree.h:51:30: error: expected unqualified-id before ‘this’ 
     parent_ = parent_ -> this; 
          ^
gTree.h:51:30: error: expected ‘;’ before ‘this’ 
+0

見上 – nickoba

回答

0

的實現是完全錯誤的。我在代碼中看到了幾個錯誤。如果在沒有子節點的根節點上調用remove(),則訪問NULL parent_。並且循環未正確佔用vector::size()未簽名。只是一般的語法錯誤。

嘗試一些更喜歡這個:

template <typename E> 
class gTNode 
{ 
    ... 
    bool remove() 
    { 
     if (parent_) 
     { 
      auto iter = std::find(parent_->children_.begin(), parent_->children_.end(), this); 
      auto index = std::distance(parent_->children_.begin(), iter); 
      parent_->children_.erase(iter); 
      if (!children_.empty()) 
      { 
       parent_->children.reserve(parent_->children_.size() + children_.size()); 
       parent_->children_.insert(parent_->children.begin() + index, children_.begin(), children_.end()); 
       for (auto *child : children_) 
        child->parent_ = parent_; 
       children_.clear(); 
      } 
     }  
     else if (!children_.empty()) 
     { 
      cout << "can't remove the root if it has children\n"; 
      return false; 
     } 

     //delete (deallocate memory of) this node 
     delete this; 
     return true; 
    } 

    friend class gTree<E>; 

private: 
    E data_; 
    gTNode<E>* parent_; 
    std::vector<gTNode<E>*> children_; 
}; 
+0

@nickoba代碼我發現並沒有改變孩子的順序編輯,所以輸入必須是在要開始使用 –

+0

有刪除節點時更改順序的方法? – nickoba

+0

@nickoba當然,你可以使用任何你想要的順序。但爲什麼要改變順序呢?除非兒童應該被分類。 –