C++模板类的insert方法
insert method of C++ template class
以下是我迄今为止实现的内容。执行后调试以下代码时"n=新节点(val,NULL,NULL);"在insert方法和离开insert方法中,一旦我离开该方法,"val"就不会保存在根节点中,我不明白为什么。
// Creates an empty binary tree
template<class T> binTree<T>::binTree() {
root = NULL;
}
template<class T> void binTree<T>::insert(T val) {
insert(val, root);
}
template<class T> void binTree<T>::insert(T val, node* n) {
if (n == NULL) {
n = new node(val, NULL, NULL); // <=============Not actually storing the value into the node after this method is done
} else if (val < n->val) {
if (n->left == NULL) {
n->left = new node(val, NULL, NULL);
} else {
insert(val, n->left);
}
} else if (val > n->val) {
if (n->right == NULL) {
n->right = new node(val, NULL, NULL);
} else {
insert(val, n->right);
}
}
}
这是头文件中我的私有结构:
private:
struct node {
T val;
node* left;
node* right;
node(T v, node* l, node* r) :
val(v), left(l), right(r) {
}
};
void destruct(node* n);
void insert(T val, node* n);
T find(T val, node* n) const;
T remove(T val, node* n, node* parent);
node* root;
};
您按值接受指针,因此您只修改局部变量n
,当函数返回时,对其的更改将丢失。
也许你想参考n
,就像node*& n
一样?这意味着函数内部对n
的更改将影响传递到函数中的参数。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- std::list 的两个 insert() 方法签名之间的实现差异
- STL vector.insert 方法期望_InputIterator作为参数
- C boost :: bimap insert()方法不起作用
- 如何为我的自定义向量类实现类似 vector.insert 的方法
- AVL树-无法将根传递给insert方法
- C++模板类的insert方法
- 自己的"Insert"方法(向量)函数模板
- 为什么map.insert()方法调用复制构造函数两次?
- C++没有默认构造函数?正在尝试为LinkedList创建Insert方法
- 新的C++11模板方法是否会使以前的C++98/03 push_back/insert方法过时
- 是否有一种方法可以在mysql_fetch_row()循环中发出下一个(如INSERT) mysql语句