データ構造を含むunordered_mapを作成しています。各ステップで、私はunordered_mapに別のキーを持つ新しい構造体を挿入する必要があります。挿入された新しい構造体は、同じ値を除いて挿入された構造体と同じです。問題は、構造Aを作成して作成したばかりの構造Bを作成した後、Aでベクトルを変更した場合、Bにも変更が適用されるということです。 私の問題をより簡単に説明するために、 I = 0ラベルを持つ第1の構造、コスト= 0、獣医= [1,2,3,4]を作成し、iがマップに挿入し、上記のコードではデータ構造を持つUnordered_map
#include <unordered_map>
#include <malloc.h>
#define Alloc(p,a,t) do \
if (!(p = (t *) malloc ((size_t) ((a) * sizeof (t))))) { \
printf("run out of memory [Alloc(%s,%d,%s)]\n",#p,a,#t); \
exit(1); \
} while (0)
using namespace std;
typedef struct{
int label;
int cost;
int *vet;
}node;
int main()
{
unordered_map<int, node> map;
std::unordered_map<int,node>::const_iterator id;
node state;
int w=4;
Alloc(state.vet,w,int);
int i,j,count=0;
state.label=count;
state.cost=0;
for(i=0;i<w;i++)
state.vet[i]=i+1;
map.insert(make_pair(count, state));//insert the first structure
//Print the first structure inserted
id=map.find(count);//search for the first structure
printf("*****First structure********\n");
printf("label %d\n",id->second.label);
printf("cost %d\n",id->second.cost);
printf("vector");
for(j=0;j<w;j++)
printf(" %d",id->second.vet[j]);
printf("\n");
count++;
id=map.find(count-1);//search for the first structure in order to copy it into the second structure
state=id->second;
state.label++;
state.cost=state.cost+2;
state.vet[3]--;
map.insert(make_pair(count, state));//insert the second structure
//Print all the structures inserted
printf("*****All structures********\n");
for(i=0;i<count+1;i++){
id=map.find(i);
printf("*************\n");
printf("label %d\n",id->second.label);
printf("cost %d\n",id->second.cost);
printf("vector");
for(j=0;j<w;j++)
printf(" %d",id->second.vet[j]);
printf("\n");
}
free(state.vet);
return 0;
}
。次に、最初の構造を2番目にコピーし、label = 1、cost = 2、vet = [1,2,3,3]というように2番目の構造を修正しました。問題は、最初の構造の獣医が変更されていることです。ラベルとコストは変更されないことに注意してください。実際の出力は次のとおりです。
*****First structure********
label 0
cost 0
vector 1 2 3 4
*****All structure********
*************
label 0
cost 0
vector 1 2 3 3
*************
label 1
cost 2
vector 1 2 3 3
これはどうしてですか? ありがとう