在模板中传递参数

Passing arguments in templates

本文关键字:参数      更新时间:2023-10-16

我正在实现一个红黑树,其中插入函数应该有两个模板,一个用于项目,另一个用于键。我以这种方式在插入函数中传递参数:

template <class Item, class Key>
void RedBlackTreeNode<Item, Key>::InsertKey(const Item *&T, const Key *&z)

我尝试在第二个参数中传递一个数组(由随机元素组成),这样:

const int* pointer = &arr[i];
t1.InsertKey(//something else here// , pointer); //insert the tree and the node

但是,我不知道要传递什么作为第一个参数才能在红色黑色树中插入元素。第一个参数代表什么?我试图通过树的根部,这样:

Node<int, int> n1;
t1.InsertKey(n1->root, pointer);

不幸的是,这是行不通的。请帮忙吗?

提前谢谢。

如果你正在实现一棵红黑树(或者甚至只是一个二叉树),你只是将要插入的元素作为参数。您正在插入一个可以与另一个项目进行比较的Item,没有Key的概念。如果要创建Key/Value容器,只需获取一个std::pair<Key, Value>项目并在item.first上进行比较,或类似的东西。

下面是二叉搜索树插入的代码模型。您可以从它开始添加必须为 [红黑树插入(http://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion) 保留的属性:

template <class Item>
void BinarySearchTreeNode<Item>::Insert(Item item)
{
   if (item < this->item)
   {
     if (this->leftChild == nullptr)
        this->leftChild = new BinarySearchTreeNode(item);
     else
        insert(this->leftChild, item);
   } 
   else 
   {
     if (this->rightChild == nullptr)
        this->rightChild = new BinarySearchTreeNode(item);
     else
        insert(this->rightChild, item);
   }
}

这里有一个示例用法(假设实现的其余部分已经完成):

BinarySearchTree<int> tree;

tree.Insert(1); // Call insert on root node