c++中带类树的实现
Implementation of tree with classes in c++
我试图实现在给定节点存储子向量的树。我已经实现了查找节点的find_index
函数。它有两个参数:Node * cur
和某些key
。我试图在insert
工作时使用此功能,但我不知道Node*
要搜索什么。这样的节点一定存在,但我不知道用哪个来调用find_index
。我也不知道我的功能是否正常工作。提前谢谢。
#include <iostream>
#include <vector>
using namespace std;
class Node{
public:
Node *parent;
vector < Node* > children;
string key;
Node(){
parent=NULL;
}
};
class tree{
public:
int size;
tree(){
size=0;
}
Node* find_index(Node *cur,string key){
Node *tmp;
if(cur->key==key){
tmp=cur;
}
if(cur==NULL){
tmp=NULL;
}
for(int i=0;i<cur->children.size();i++){
find_index(cur->children[i],key);
}
return tmp;
}
void add(){
string father,son;
while(cin>>father>>son){
if(find_index(?,father)==NULL){//I don't know what node to put instead of question mark and is my function working
size++;
Node *newnode=new Node();
newnode->key=father;
newnode->parent=NULL;
}
else if(find_index(t,son)==NULL){
size++;
Node *newnode1=new Node();
newnode1->key=son;
newnode1->parent->children.push_back(newnode1);
}
else{
Node *newnode2=new Node();
newnode2->key=father;
Node *newnode3=new Node();
newnode3->key=son;
newnode2->children.push_back(newnode3);
newnode3->parent=newnode2;
}
}
}
};
我怀疑你的代码是否有效。我可以看到以下问题:
-
find_index
:如果cur为NULL,则cur->key
(在第一个if
中)发生段故障 -
find_index
:你从不评估底循环的结果 -
add
:您需要为?
部分存储树的根。
我不知道,你的输入实际上是什么样子的。我们可以存储一个根,如果我们知道输入描述的是一棵自上而下的树。我将在add
期间存储多个根。这样,你也可以自底向上构建你的树。
一个可能的解决方案是这样的
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的