我正在创建一个包含数据结构的unordered_map。在每个步骤中,我需要在unordered_map中插入一个具有不同键的新结构。插入的新结构等于刚插入的另一个,但相同的值除外。问题是,如果我创建的结构A等于刚创建的另一个结构B,然后我在A中修改了向量,则更改也应用于B. 我报告以下简单示例以更好地解释我的问题。
#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;
}
在上面的代码中,我创建了一个第一个结构,其中label = 0,cost = 0,vet = [1,2,3,4]并将其插入到地图中。然后我复制第二个结构中的第一个结构,我修改了第二个结构,使得label = 1,cost = 2,vet = [1,2,3,3]。问题是第一个结构中的兽医被修改了。请注意,标签和成本不会被修改。实际上输出如下:
*****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
为什么会这样? 谢谢
答案 0 :(得分:1)
在两者中修改兽医的原因是因为你有一个指向数组的指针,你没有为副本创建一个新的指针,所以它只是复制地址。
如果您希望第二个副本拥有自己的版本,则需要编写复制构造函数。
示例:http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor/