尝试使二叉搜索树适应两个参数,崩溃(C++)
Trying to Adapt Binary Search Tree for Two Parameters, Getting Crash (C++)
对于赋值,我需要实现二叉搜索树的几个函数。我得到了看似逻辑的代码,但是,每当我尝试实现插入节点功能时,我都会遇到程序崩溃。这是我的插入函数代码:
void insert (K k, V v)
{
TreeNode<K,V> * treeNode = NULL;
TreeNode<K,V> *temp=NULL;
TreeNode<K,V> *prev=NULL;
temp = root;
while(temp) //This is the loop that causes a crash, even if I remove the loop.
{
prev = temp;
if (temp->key < treeNode->key)
temp = temp->right;
else
temp = temp->left;
}
if (prev==NULL)
root = treeNode;
else
{
if (prev->key<treeNode->key)
prev->right = treeNode;
else
prev->left = treeNode;
}
}
我还将包括 TreeNode 类:
template <class K, class V> class TreeNode
{
public:
TreeNode(K k, V v): key(k), value(v), left(0), right(0) {}
K key;
V value;
TreeNode<K,V> *left;
TreeNode<K,V> *right;
template <class X, class Y> friend std::ostream & operator
<< (std::ostream &s,const TreeNode<X,Y> &t);
};
当我尝试执行命令t.insert("bob","bobdata")时; bam,立即崩溃。我已经注释掉了各种参数,并发现指示的部分是问题所在,尽管除此之外我卡住了。即使我删除循环并且只执行一次,它也会发生,所以我不会陷入无穷大。我觉得这可能与我传递字符串的事实有关,但我不确定,如果这是问题所在,我没有足够的知识来解决它。 有没有人可以告诉我我在这里做错了什么?非常感谢!
您是否在
循环之前将treeNode
分配给任何地方? 看起来treeNode
是NULL
所以当你在条件中取消引用它时,它会抛出一个异常:
if (temp->key < treeNode->key) // This throws an exception if treeNode is not set
^^^^^^^^^^^^^
下面的示例实现,
你需要支持 c++11 才能编译(因为nullptr
,为了兼容 C++ 而用 NULL
替换)。
#include <iostream>
using namespace std;
template <template<class K, class V> class TreeNode, class K, class V>
std::ostream & operator<< (std::ostream &s,const TreeNode<K,V> &t);
template <class K, class V>
class TreeNode
{
public:
typedef TreeNode<K,V> SelfType;
TreeNode(K k, V v): key(k), value(v), left(nullptr), right(nullptr) {}
K key;
V value;
SelfType *left;
SelfType *right;
friend std::ostream & operator<< <>(std::ostream &s,const SelfType &t);
};
template <class K, class V>
struct Tree {
typedef TreeNode<K,V> NodeType;
NodeType *root;
Tree() : root(nullptr){}
void insert (K k, V v)
{
NodeType * treeNode = new NodeType(k,v);
NodeType *temp = nullptr;
NodeType *prev = nullptr;
temp = root;
while(temp) {
prev = temp;
if (temp->key < treeNode->key)
temp = temp->right;
else
temp = temp->left;
}
if (prev==nullptr)
root = treeNode;
else {
if (prev->key<treeNode->key)
prev->right = treeNode;
else
prev->left = treeNode;
}
}
};
int main(){
Tree<int,int> t;
t.insert(1,2);
}
我只对K
和V
模板参数使用 int
进行了测试,因为它避免了与复制构造函数相关的任何问题。您可能希望让所有方法都引用K
和V
而不是纯值。
遇到了一个问题:
-
NULL
初始化treeNode
变量insert
代码中可能存在的问题:
Tree
类中未初始化的root
。
相关文章:
- 为什么模板参数推导不适用于仅指定前两个参数的可变参数模板类?
- C++如何在 switch 语句中放置两个参数
- 为什么我不能用两个参数重载 C++ 运算符 []?
- C++添加检查以避免读取两个参数
- 宏的定义从一个值创建两个参数
- C++ 如何使用一个参数从派生类构造函数中调用具有两个参数的超类构造函数
- 通过将两个参数包的元素线程化为类型对来解压缩这两个参数包
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- 错误:函数调用中有两个参数
- Qt 线程两个参数
- 为什么lambda函数用于stl函数,例如sort(),c 中的max_element()函数以两个参数为输入
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 具有两个参数的 Decltype 修改类型
- 将两个参数传递到谓词remove_if
- 同时扩展两个参数包
- 用两个参数调用新操作员,但没有分配
- 在Variadic模板中交换两个参数
- C CPPUNIT_ASSERT具有两个参数
- 具有两个参数的乘法函数
- 使用一个可选参数获取两个参数到main