我想创建一个非二叉树。我想到了带有指针的指针的这种类型的结构

struct tree{
    string name;
    int sonc;
    tree** son;
};


两个大条目我都崩溃了

void insertSon(tree* &a, string n){

if (a->sonc==0){
    a->son= new tree*;}

a->son[a->sonc]= new tree;
a->son[a->sonc]->name=n;
a->son[a->sonc]->sonc=0;
a->sonc++;}


而且在取消

void deleteTree(tree* &a){
for (int i=0;i<(a->sonc);++i){
    deleteTree(a->son[i]);
}
delete a;}


树木种群的主要cpp

tree *tree1;
tree1=new tree;


tree1->name="C:\\TEMP";
tree1->sonc=0;
insertSon(tree1,"C:\\TEMP\\aadvfdbdsbdfgfile1.txt");
insertSon(tree1,"C:\\TEMP\\aadvfdbdsbdfgfile2.txt");
insertSon(tree1,"C:\\TEMP\\FOLDER1");

tree *lastf1=tree1->son[tree1->sonc-1];
insertSon(lastf1,"C:\\TEMP\\FOLDER1\\aadvfdbdsbdfgfile3.txt");
insertSon(lastf1,"C:\\TEMP\\FOLDER1\\aadvfdbdsbdfgfile4.txt");
insertSon(lastf1,"C:\\TEMP\\FOLDER1\\FOLDER2");

tree *lastf2=lastf1->son[lastf1->sonc-1];
for (int i=0;i<100;++i){
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfile5.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfile6.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfile7.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfile8.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfile9.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfileA.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfileB.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfileC.txt");
insertSon(lastf2,"C:\\TEMP\\FOLDER1\\FOLDER2\\aadvfdbdsbdfgfileD.txt");
}

最佳答案

您的代码在此行中是错误的:

a->son= new tree*;


仅分配一个指针,但是您尝试将其用作指针数组。

不要使用数组,而应该使用vector。你可以有

std::vector< tree * > son;


当然,您仍然需要注意向量中的指针。如果孩子可用,可以使用shared_ptr<tree>unique_ptr<tree>

std::vector< shared_ptr< tree > > son;


要么

std::vector< unique_ptr< tree > > son;


(在shared_ptrunique_ptr中使用namespace stdnamespace boost

关于c++ - 非二叉树C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13034465/

10-11 06:12