gpt4 book ai didi

c++使用指针和状态机构建递归树

转载 作者:太空宇宙 更新时间:2023-11-04 14:14:30 25 4
gpt4 key购买 nike

我有一个简单的状态机(在下面输入)。我的主要问题是我正在尝试对作为我的状态机的函数进行递归调用。我在进入该函数时所做的是为我的树创建一个新节点,然后将其推送。当我进行递归调用时,我一遍又一遍地创建一个新节点。这可以工作,但是在将 child 添加到 parent 时我有点困惑。有人可以帮忙看看这个并帮我拿走我的树节点(我假设是父节点)并将一个 child 附加到它上面吗?

TreeNodeClass* ProcessTree(TokenT token, vector <list <stateAssoc> >& vecTree, int depth)
{
int state = 1; //Assume this is a new record.
bool noState = false;
bool update = true;
int dex = 0;
string root, value, data, tag;
TreeNodeClass* treeNode;

treeNode = new TreeNodeClass; //Assume a new node per state machine visit.

//Need 11 to break out of loop as well.
while(state != 10)
{
switch(state)
{
case 1: dex = 1;
break;

case 2: dex = 6;
root = yylval;
break;

case 3: dex = 7;
break;

case 4: dex = 3;
value = yylval;
treeNode->CreateAttrib(root, value);
break;

case 5: dex = 2;
break;

case 6: dex = 4;
data = yylval;
break;

case 7: //Really Don't do anything. Set the tag creation at 8...
dex = 8;
tag = yylval;
if(data != "" and data != "authors")
treeNode->CreateTag(data, tag);
break;

case 8: {
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode);
}
token = TokenT(yylex()); //Get a new token to process.
dex = 5;
break;

case 9: dex = 9;
update = false;
if(yylval != treeNode->ReturnTag())
{
state = 11;
}
break;

case 10: update = false;
treeNode->SetHeight(1);
break;

default: cout << "Error " << endl;
cout << state << endl;
cin.get();
break;

}

if(!noState)
state = FindMatch(vecTree[dex], token);

if(update)
token = TokenT(yylex());
else
update = true;
}
return treeNode;

}

您可以假设 dex 只是一个列表数组的索引,它将返回正确的状态或 11(错误)。您还可以假设此函数至少已在输入文件上调用一次并已开始解析。感谢您的帮助。

最佳答案

看看你的代码,你有

int state = 1;
//Code

while(state != 10) {
switch(state) {
case:1 dex = 1; break; //Only case you run
//more cases
case 8: { //never enter here
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode); //should work if assuming function is correct
}
//stuff
break;
default: break;//blah
}
}
//blah

return treeNode;

除了 state 始终等于 1 之外,我看不到其他原因,您的代码在案例 8 中会失败。这是假设 treeNodeClass::AddChildren(TreeNodeClass*) 已正确实现。如果没有该代码,我可以假设这不是您的问题。是否有一些方法可以使 state 在 switch 中不为 1?

关于c++使用指针和状态机构建递归树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com