我正在尝试定义一组模板类来表示 C++ 中的搜索树。
在 find 方法中,我需要返回包含给定键的节点指针(表示为指针);这样我将重用find方法来实现插入和删除。
template <class K, class R>
struct Node {
K key;
R record;
inline Node(K k, R r) {
this->key = k;
this->record = r;
}
};
template <class K, class R>
struct BST_Node : public Node<K,R> {
BST_Node<K,R> *sx;
BST_Node<K,R> *dx;
inline BST_Node(K key, R record)
: Node<K,R>(key, record) {
this->sx = NULL;
this->dx = NULL;
}
BST_Node<K,R> **find(K k) {
BST_Node<K,R> **p = k < this->key ? &this->sx : &this->dx;
while (*p && k != (*p)->key)
p = k < (*p)->key ? &(*p)->sx : &(*p)->dx;
return p;
}
/* other methods */
};
只有一个小问题:如果 key 在根目录中怎么办?
我无法返回 &this because this ,那我该怎么办?
因为我想使用指向指针的指针的原因是这样我可以返回 NULL 指针的地址,所以对于插入我可以写这样的东西:
BST_Node<K,R> *insert(K k, R r) {
BST_Node<K,R> **p = this->find(k);
if (*p == NULL) //if the search fails
*p = new BST_Node<K,R>(k, r);
return *p;
}
最佳答案
你不清楚。 在你的例子中,指针 this 有一个类型
BST_Node<K,R>* const
意思是不能改变方向(不知 Prop 体怎么描述,比如指针指向的地址..)。如果你回来
//BST_Node<K,R>**
return &this;
这意味着您可以通过返回值更改this 的值。这是不允许的。所以出现错误。
这里为什么要返回双指针?
我看到了你的版本,我想你可以在函数 find() 中返回一个 NULL 来表示你在根目录下找到了 key 。当你写一个递归的 find 函数时会有点复杂,但是因为你使用的是循环,你可以在 find 函数的最开始添加一个 if 语句。在insert函数中这样写:
if (p == NULL) //if returns the root
/*do sth.*/
小提示,我从不在根目录下保存任何数据,当我使用树时,通常我的树根和树的生命周期一样长。
关于c++ - 在 C++ 中返回指向对象指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22799467/