0

我已经开始玩结构,我创建了一个我称之为LR

struct LR{
    int v;
    LR* L;
    LR* R;
};

我了解如何以通用方式操作它 -main下面的代码,在我开始构建类之前,我已经开始编写递归函数,它以字符串(“LRLRR”)的形式获取 LR 中节点的“地址”并返回需要LR,但我仍然从编译器中得到错误:

LR.cpp In function 'LR chooseNode(LR*, std::string)':    
LR.cpp [Error] request for member 'L' in 'tree', which is of pointer type 'LR*'   

(maybe you meant to use '->' ?)- 部分带有递归的行错误chooseNode(*tree.L,str2);

我在做什么错,或者更确切地说如何调试它?(除了我的实施的整个概念,这是相当练习)。

#include<iostream>
#include<string>
#define SHOW(a) std::cout << #a << ": " << (a) << std::endl
using namespace std;
struct LR{
    int v;
    LR* L;
    LR* R;
};

LR chooseNode(LR* tree, string str){// for example str="LRL"    

            // for clarity I've cutted the most of the code

            if(str[0]=='L')
            chooseNode(*tree.L,str2);   
        else if(str[0]=='R')
            chooseNode(*tree.R,str2);

};


int main(){

    LR d1,d2,d3;
    d1.v=4; 
    d1.L=&d2;
    (*(d1.L)).L=&d3;
    d3.v=12345;
    SHOW((*(*d1.L).L).v);


    cout<<"Opis: "<<"\n";
    SHOW(int(&d1));
    SHOW(int(&d2));
    SHOW(sizeof(d2.v));

    return (0);
}
4

2 回答 2

1

我究竟做错了什么?

tree是一个类型的指针LR*

可以使用以下语法从指针访问结构成员:

tree->L

或者(不太常见,但它看起来像你正在尝试的)

(*tree).L

或者更确切地说如何调试它?

“调试”是对成功构建的可执行文件执行的过程。你有一个编译器错误,所以调试不适用。

于 2013-03-03T23:58:18.120 回答
1

@Qbik - 开始考虑你的字符串处理和效率,最终得到了这个,我不妨与你分享:

LR* chooseNodeUsingCString(LR* tree, const char* str){// for example str="LRL"
    // Pre-conditions
    if ((str[0] == 0) || (tree == 0))
        return 0; // or assert or whatever

    // This assumes an L unless an R, but handle however if needed.
    LR* next = tree->L;
    if (str[0]=='R')
        next = tree->R;

    // End of path case
    if (str[1] == 0)
    {
        return next;
    }

    // Error case, path string does not exist in the tree.
    if (!next)
        return 0;

    // Standard recurse case; easy iteration with no copying along a C-String.
    const char* pathStringWithFirstElementRemoved = str + 1;
    return chooseNodeUsingCString(next, pathStringWithFirstElementRemoved);
};
于 2013-03-04T00:52:55.740 回答