0

が順序付けられたリストを要求したときに、各 elemType オブジェクトを正しい順序で順序付きリスト ベクトルに追加するmainために使用するバイナリ ツリー クラスを取得できるように、バイナリ ツリー内にベクトル リストを配置したいと考えています。inorder次に、このリストが返されるか公開されてアクセスされるため、バイナリ ツリーから 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 に答える