私はバイナリ検索ツリーの挿入関数を作成しようとしていました。しかし、最初はnullであるグローバル変数を置き換えることができませんが、2ホップ離れた(すなわちパラメータを介して)NULL以外のグローバル変数を置き換えることができます。次のコードは、問題の内容を示しています。2ホップ離れたグローバル変数を置換できません
struct tree{
int a;
tree* right;
tree* left;
};
tree* root=NULL;
void insert(tree* in, int b){
if(in){
if(in->a<b)
insert(in->right,b);
else if(in->a>b)
insert(in->left,b);
else
cout<<"the value is already in the tree."<<endl;
}else{
tree* temp = new tree;
temp->a=b;
temp->right=NULL;
temp->left=NULL;
in=temp;// this does not change the root(global variable) value
}
}
なぜin = tempがグローバル変数を何らかの形で変更するとは思いますか?ローカル変数(関数パラメータ)に代入しています。 –
生ポインタを 'unique_ptr <>'に置き換えると、人生はもう少し簡単になります... – Nim