我将AST类型的变量传递给函数替换,然后由于未知原因而更改,下面是代码。
这个替换函数将AST中的每个非布尔变量更改为布尔值,并且即使在main函数中执行此函数后,原始AST也会更改,我不希望AST原始更改,请帮忙!!对不起,如果我的代码缩进很奇怪。
struct AST {std::string info; pNODE children[2]; };
void subHelper (AST *T, string a, string b){
if (T->children[0]==NULL&&T->children[1]==NULL){
if (T->info.compare(a)==0)
{
T->info = b;
}
return;
}
if (T->children[0]!=NULL){
subHelper((T->children[0]), a,b);
}
if (T->children[1]!=NULL)
subHelper((T->children[1]), a,b);
}
AST substitute(list<bool> vals, list<string> vars, AST original)
{
int a = vals.size();
int b = vars.size();
if (a==b)
{
//cout<<"\n";
//prinTree(original);
//cout<<"\n";
//attempt of trying to save original by copying it
AST value;
value.info=original.info;
value.children[0]=original.children[0];
value.children[1]=original.children[1];
for (it2 = vals.begin(), it=vars.begin(); it2 != vals.end(); it++,
it2++)
{
if(*it2 == false)
{
subHelper(&value, *it, "F");
}
else
{
subHelper(&value, *it, "T");
}
}
// prinTree(Exp);cout<<"\n";
//prinTree(value);cout<<"\n";
return value;
}
else
{
return original;
}
}
答案 0 :(得分:0)
您的子数组似乎保存了指针,因此您的值副本是浅副本而不是原始的深层副本 - 在树的更深层次上,它们保持不变,因此更改会反映到两者。
答案 1 :(得分:0)
好的家伙感谢你指出我的错误,这是我尝试深层复制,似乎有效。
void deepcopy(AST *dest, AST *source){
if (source->children[0]==NULL&&source->children[1]==NULL){
dest->info=source->info;
return;
}
dest->info=source->info;
AST *node = new AST();
if (source->children[0]!=NULL){
dest->children[0]=node;
deepcopy((dest->children[0]), source->children[0]);
}
if (source->children[1]!=NULL){
dest->children[1]=node;
deepcopy((dest->children[1]), source->children[1]);
}
}