我正在尝试使用模板实现红黑树。例如,向树中插入一个项目时,键和项目都应该是泛型类型。到现在为止,我实现了一个头文件,它由一个结构体和要实现的函数组成。但是,我不知道我是否以正确的方式使用模板。另外,当我尝试实现“插入”功能时,IDE 给出了错误: “void RedBlackTree::InsertKey(Item*&, Key*&)”的原型(prototype)与类“RedBlackTree”RedBlackTree.h 中的任何内容都不匹配
这是我的头文件:
#ifndef REDBLACKTREE_H_
#define REDBLACKTREE_H_
template <class Item, class Key>
class RedBlackTree
{
typedef enum
{
BLACK,
RED
}ColourNode;
typedef struct RBT
{
struct RBT *left;
struct RBT *right;
struct RBT *parent;
struct RBT *root;
ColourNode colour;
Item item;
Key key;
}RBTNode;
public:
~RedBlackTree(); // destructor
RedBlackTree(Item, Key); // default constructor
void InsertKey(Item, Key);
int InsertFixUp(Item, Key);
int RemoveKey(Item, Key);
int FindKey(Item, Key);
private:
RedBlackTree<Item, Key> *rootPointer;
RedBlackTree<Item, Key> *NILL_LEAF;
};
template <class Item, class Key>
void RedBlackTree<Item, Key>::InsertKey(Item *&T, Key *&z)
{
//node* nil=tree->nil;
//node* root=tree->root;
RBTNode *y;
RBTNode *x;
y=T->nil;
x=T->root;
while(x != T->nil)
{
y=x;
if((z->key)<(x->key))
x=x->left;
else
x=x->right;
}
y=z->parent;
if(y == T->nil)
z=T->root;
else
if((z->key)<(y->key))
z=y->left;
else
z=y->right;
z->left=T->nil;
z->right=T->nil;
z->colour=RED;
InsertFixUp(T,z);
}
#endif /* REDBLACKTREE_H_ */
提前致谢。
最佳答案
问题是 InsertKey
的参数类型与声明不匹配。在声明中参数是 Item
和 Key
,在实现中它们是 Item*&
和 Key*&
(对指针的引用)。这些需要匹配。
void InsertKey(Item, Key);
^^^^ ^^^
void RedBlackTree<Item, Key>::InsertKey(Item *&T, Key *&z)
^^^^^^^ ^^^^^^
关于c++ - 在 C++ 中使用模板和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814613/