0

这是我第一次尝试在 C++ 程序中处理多个类,体验非常糟糕,因为我花了几十个小时盯着代码并试图找出问题所在。另外,我目前的实际代码大约是 600 行,所以我将把相关代码放在最困扰我的地方并尝试解释它。

我有一个名为 node 的多路搜索树类。我的目标是使用 AVL 树(类名 Avlnode)作为索引树(包含按排序顺序排列的单词和每个 Avlnode 上相应节点的地址),以便在 O(记录 n) 时间。现在考虑这个代码片段

//Basically searches for a string in Avl tree with root t and returns pointer 
//to the   corresponding node in the multi-way tree 

node* Avlnode::Avlsearch(string x,Avlnode* t)
{
    if (t==NULL)
    {
        cout<<"why you search whats not in string";//invalid search
        exit(0);
    }
    else
    {
        if(isLess(x,t->element)) //isLess compares strings and works good
        {                        //element refers to the string stored in Avlnode
            Avlsearch(x,t->left);
        }
        else if (isLess(t->element,x))
        {
            Avlsearch(x,t->right);
        }
        else
        {
            cout<<"found";  
            cout<<t->index->empname;
            return t->index; //its fine till here
        }
    }
}

//basically adds child under the boss in multi-way tree, by searching for the
//address of boss first using the AVL tree

void node::insertunderboss(string child, string boss,Avlnode* obj1)
{
    node* temp=obj1->Avlsearch(boss, obj1->root); //root=root of Avltree
//why is address of temp and t->index not the same??
    cout<<temp;
    cout<<"root current is "<<obj1->root->element;
    cout<<"\n"<<temp->empname; //empname is string stored in node
 //this refuses to work even though t->index->empname worked perfect.
 // in my first function t->index->empname gave me a string
 // I just stored t->index inside temp
 //But temp->empname makes cmd hang. Your program has stopped working. 
    node* c=insertemp(child,temp);
    cout<<"last check";
    obj1->Avlinsert(c,obj1->root);
    return;
}

我希望我的问题很清楚。我想通过引用传递,但我无法弄清楚为什么这不起作用,从逻辑上讲它看起来没问题。任何形式的帮助将非常感激。

4

1 回答 1

3

看起来您缺少返回语句,这是一个改进

node* Avlnode::Avlsearch(string x,Avlnode* t)
{
    if (t==NULL)
{
    cout<<"why you search whats not in string";//invalid search
    exit(0);
}
else
{
    if(isLess(x,t->element)) //isLess compares strings and works good
    {                        //element refers to the string stored in Avlnode
        return Avlsearch(x,t->left);
        ^^^^^^
    }
    else if (isLess(t->element,x))
    {
        return Avlsearch(x,t->right);
        ^^^^^^
    }
    else
    {
        cout<<"found";  
        cout<<t->index->empname;
        return t->index; //its fine till here
    }
}
}
于 2013-09-13T20:24:30.827 回答