在模板中传递参数
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
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用