问题描述
我正在使用 BST 作为字典类的派生类创建字典。因为我正在使用模板,所以我遇到了一个错误,我找出了原因但无法解决它。谁能弄清楚?谢谢
代码如下:
#include <iostream>
#include <utility>
using namespace std;
template <class K,class E> class BST;
template <class K,class E>
struct pair{K first; E second;};
template <class K,class E>
class TreeNode {
friend class BST <K,E>;
public:
K data;
TreeNode<pair<K,E>> *leftChild;
TreeNode<pair<K,E>> *rightChild;
};
template <class K,class E>
class Dictionary {
public:
virtual bool IsEmpty() const = 0; // return true if dictionary is empty
virtual pair<K,E>* Get(const K&) const = 0;
// return pointer to the pair w. specified key
virtual void Insert(const pair <K,E>& k) = 0;
// insert the given pair; if key ia a duplicate,update associate element
virtual void Delete(const K& k) = 0; // delete pair w. specified key
};
template <class K,class E>
class BST:public Dictionary<K,E> {
public:
BST();
pair<K,E>* Get(const K& k)const;
pair<K,E>* RankGet(int r);
pair<K,E>* Get(TreeNode <pair <K,E>>* p,const K& k)const;
bool IsEmpty() const;
void Insert(const pair<K,E >& thePair);
void Delete(const K& k);
private:
TreeNode <pair<K,E>> *root;
};
template<class K,class E>
BST<K,E>::BST(){root = nullptr;}
template <class K,class E>
pair<K,E>* BST<K,E> :: Get(const K& k) const
{// Driver
return Get(root,k);
}
template <class K,class E>
bool BST<K,E>::IsEmpty() const
{
return root==nullptr;
}
template <class K,E>::Get(TreeNode <pair <K,const K& k)const
{// Workhorse
if (!p) return 0; //empty
if (k < p->data.first) return Get(p->leftChild,k);
if (k > p->data.first) return Get(p->rightChild,k);
return &p->data;
}
template <class K,E>::RankGet(int r) //search by rank
{ //search the BST for the rth smallest pair
TreeNode < pair<K,E>> * currentNode = root;
while (currentNode) {
if (r < currentNode -> leftSize)
currentNode = currentNode -> leftChild;
else if (r > currentNode -> leftSize)
{
r -= currentNode -> leftSize;
currentNode = currentNode -> rightChild;
}
else return & currentNode -> data;
}
return 0;
}
template <class K,class E>
void BST<K,E > :: Insert(const pair<K,E >& thePair)
{ // insert thePair into the BST
// search for thePair.first,pp parent of p
TreeNode < pair<K,E>> *p = root,*pp = 0;
while (p) {
pp = p;
if (thePair.first < p->data.first) p = p->leftChild;
else if(thePair.first > p->data.first)p = p->rightChild;
else // duplicate,update associated element
{ p->data.second = thePair.second; return;}
}
// perform insertion
p = new TreeNode< pair<K,E>> (thePair);
if (root) // tree is nonempty
if (thePair.first < pp->data.first) pp->leftChild = p;
else pp->rightChild = p;
else root = p;
}
int main()
{
BST<int,char> bst;
pair<int,char> p;
int A[11]= {50,3,30,40,80,35,2,20,15,60,70};
char B[11]= {'a','b','c','d','e','f','g','h','i','j'};
for(int i=0; i<11; i++)
{
cout<<A[i]<<" "<<B[i]<<endl;
//maxHeap.Push(A[i]);
}
return 0;
}
我知道 TreeNode 应该有 2 个模板参数我试图给它“K”作为 pair
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)