【问题标题】:Passing arguments in templates在模板中传递参数
【发布时间】:2014-01-16 10:01:37
【问题描述】:

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

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 可能是映射中存储的值的类型。
  • 我收到三个错误:无效参数候选者是:void InsertKey(const int * &, const int * &),无法解析字段 'root' 并且 '->' 的基本操作数有非指针类型 'Node'
  • 你为什么在这里使用指针?
  • 我不知道如何实现红黑树的另一种方法,并且我有使用两个模板的限制。

标签: c++ tree


【解决方案1】:

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

这是binary search tree 插入的代码模型。您可以从它开始添加必须为[红黑树插入(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

【讨论】:

  • 所以我的插入方法不能带两个参数?
  • @user3136756 不是它不能接受两个参数,而是第二个参数是什么?如果您对第二个参数的使用有解释/理由,请继续:)但是基本的红黑树(或二叉树)只需要一个值或项插入节点。
  • 嗯,这是我的问题,我不知道要为第二个参数传递什么。我被要求实现这个问题,并且有人说在添加项目时,键和项目都应该是通用类型(C++ 中的模板)。因此,我认为我必须使用两个模板,但我得出的结论是使用两个模板没有任何意义!
猜你喜欢
  • 2021-11-24
  • 2021-09-26
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
相关资源
最近更新 更多