Unordered_map со структурами данных

Я создаю 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

Почему это происходит? Спасибо


person Tropic_coding    schedule 23.12.2016    source источник


Ответы (1)


Причина, по которой ветеринар изменен в обоих случаях, заключается в том, что у вас есть указатель на массив, вы не создаете новый указатель для копии, поэтому он просто копирует адрес.

Если вы хотите, чтобы вторая копия имела свою собственную версию, вам нужно будет написать свой конструктор копирования.

Пример: http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor/

person AresCaelum    schedule 23.12.2016