Reputation: 11
I am creating an unordered_map containing data structures. At each step i need to insert a new structure with a different key in the unordered_map. The new structure inserted is equal to another just inserted with the exception of same values. The problem is that if i create a structure A equal to another structure B just created and then i modified vectors in A, the changes are applied also to B. I report the following simple example to better explain my problem.
#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;
}
In the code above i create a first structure with label=0,cost=0,vet=[1,2,3,4] and i insert it into the map. Then i copy the first structure in a second one and i modified the second structure such that label=1,cost=2,vet=[1,2,3,3]. The problem is that vet in the first structure is modified. Notice that label and cost are not modified. In fact the output is the following:
*****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
Why this happens? Thank you
Upvotes: 1
Views: 992
Reputation: 1566
The reason the vet is modified in both is because you have a pointer to the array, you are not creating a new pointer for the copy so it is just copying the address over.
If you want the second copy to have its own version then you will need to write your copy constructor.
Example: http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor/
Upvotes: 1