从二叉树类模板中获取有序的对象向量

时间:2013-05-27 07:37:28

标签: c++ templates binary-tree binary-search-tree

我希望在二叉树中有一个向量列表,这样当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

1 个答案:

答案 0 :(得分: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);
    }
  }
};