简体   繁体   English

插入map- key始终存在

[英]insertion to map- key is always exist

I have an issue with inserting values to map. 我在插入要映射的值时遇到问题。

#define SIZE 5
#define pair<unsigned char *, int> pair_t

struct myCmp
{
   int operator()(const unsigned char arr_1[SIZE], const unsigned char arr_2[SIZE])
   {
     printf("arr_1: %02x,%02x,%02x,%02x,%02x  arr_2: %02x,%02x,%02x,%02x,%02x", 
                  arr_1[0], arr_1[1],arr_1[2],arr_1[3],arr_1[4],
                  arr_2[0],arr_2[1],arr_2[2],arr_2[3],arr_2[4]);
   }
} 
void main()
{
  map<unsigned char *, int, myCmp> myMap;
  map<unsigned char *, int, myCmp>::iterator it;

  unsigned char arr[SIZE] = {'\0'};

  //---- first insertion ----//

  arr[0] 0xa;
  pait_t data_1(arr,1);
  pair< map<unsigned char *, int, myCmp>::iterator> ret_1 = myMap.insert(data_1);

  if(ret_1.second)
    printf("added one");

  else
    printf("already exist one");



 //---- second insertion ----//

  arr[1] 0xb;
  pait_t data_2(arr,2);
  pair< map<unsigned char *, int, myCmp>::iterator> ret_2 =  myMap.insert(data_2);

  if(ret_2.second)
    printf("added two");

  else
    printf("already exist two");
}

the first insertion is ok, myCmp is not activated yet and I get added one 第一次插入没问题, myCmp尚未激活,我added one

the problem is with the second insertion, it seems that myCmp gets the same two arrays and always return 0 (equal)- it prints arr_1: ab arr_2: ab so the ret_2.second is false (key is already exist) and prints already exist two . 问题是第二次插入,看来myCmp会得到相同的两个数组,并且总是返回0(等于)-它会打印arr_1: ab arr_2: ab所以ret_2.second为false(键已经存在)并且打印already exist two

I tried to change the value of arr, but it doesn`t have any affect. 我试图更改arr的值,但是它没有任何影响。

the strange part is when I tried to do the same but instead of char * I used string (changed the all the signatures of course..), the myCmp function got two different values. 奇怪的是,当我尝试执行相同的操作但不使用char *我使用了string (当然更改了所有签名。), myCmp函数得到了两个不同的值。

I can`t use string as key.. 我不能使用字符串作为键。

I don't know why it behaves like this and myCmp gets two identical values. 我不知道为什么它会这样,并且myCmp获得两个相同的值。

I will be happy for guidance on that matter. 我很乐意为您提供指导。

You're giving the arr address that is the same in both cases. 您提供的arr地址在两种情况下都相同。 Try using a std::string . 尝试使用std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM