0

我想在二叉树中有一个向量列表,这样当main要求一个有序列表时,我可以获取二叉树类,用于inorder将每个 elemType 对象以正确的顺序添加到 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

4

1 回答 1

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);
    }
  }
};
于 2013-05-27T08:09:15.880 回答