2013-05-27 39 views
0

我想在二叉樹內部有一個矢量列表,這樣當main要求有序列表時,我可以使用inorder來使用二叉樹類添加每個elemType對象按正確的順序放入orderedList向量中。然後這個列表將被返回或公開並被訪問,以便我可以從二叉樹中得到orderedList。從二叉樹類模板獲取對象的有序矢量

我不能使用cout,因爲數據類型更復雜,需要在矢量內完全返回。

我的代碼做了一些意見,以更好地說明我的問題:

BinaryTree.h

// I am using this tree mainly with a data class that holds different data 
// types (int, string, ect...) 

// This is my node in the binary tree 
template <class elemType> 
struct nodeType 
{ 
    elemType info; // create the variable to hold the data 
    nodeType<elemType> *lLink; 
    nodeType<elemType> *rLink; 
}; 

template <class elemType> 
class BinaryTree 
{ 
    public: 

    // I want to use inorder to put a ordered list of the tree contents 
    // into the orderedList 
    vector<elemType> orderedList; 

    void inorder (nodeType<elemType> *p) const; 

}; 

// definitions: 

template <class elemType> 
void BinaryTree<elemType>::inorder(nodeType<elemType> *p) const 
{ 
    // Instead of using cout I want to push_back the elemType object 
    // into the orderedList vector (because I want to return the vector 
    // to main so I can list the details inside the elemType object 
    if (p != NULL) 
    { 
      // the big issue is right here, how to push_back to the orderedvector 
      // and get the elemType inside the node into the vector? 
      inorder (p -> lLink); 
      cout << p -> info << " ";// I can't use cout! 
      inorder (p -> rLink); 
    } 
} 

編輯:

我嘗試使用orderedList.push_back(p -> info);

代替cout,我得到這個錯誤:

error C2663: 'std::vector<_Ty>::push_back' : 2 overloads have no legal conversion for 'this' pointer

回答

0

void inorder (nodeType<elemType> *p) const;是一個const成員函數。您不能(邏輯)修改此函數中的BinaryTree實例。 inorder應該只返回一個這樣的載體:

template <class elemType> 
class BinaryTree 
{ 
public: 
    vector<elemType> inorder (nodeType<elemType> *p) const { 
    vector<elemType> v; 
    add_inorder(v, p); 
    return v; 
    } 

private: 
    void add_inorder(vector<elemType>& v, nodeType<elemType>* p) 
    { 
    if (p != NULL){ 
     add_inorder(p -> lLink); 
     v.push_back(p); 
     add_inorder(p -> rLink); 
    } 
    } 
}; 
+0

當我打電話序功能從主我得到的是序時間超過零個參數的誤差。但我不能添加論據。見:vector tmp; tmp = JoesBinaryTree.inorder();' – Joseph

+0

@Joseph你是這個函數的作者,你應該知道該傳遞或不傳遞給函數。您原始帖子中的'inorder'函數採用了'nodeType *'類型的argumetn。如果這個指針應該指向一個內部節點(第一個節點??),則移除該參數並從'inorder'中傳遞給'add_inorder' – hansmaad