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
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
.
I tried to change the value of arr, but it doesn`t have any affect.
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.
I can`t use string as key..
I don't know why it behaves like this and myCmp
gets two identical values.
I will be happy for guidance on that matter.
You're giving the arr address that is the same in both cases. Try using a std::string
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.