I have a map of pair as key and bool as value. When i try to find a certain pair that is already included using map::find method, it's not finding any item. What do i do wrong?
I tried to implement a comparator class and set it as key_comp in map, but I'm not sure i did it right. Is this the solve?
I am working in VS12, I attached a photo with the debugging, you shall understand much more from that:
You are calling find
with pair<char *, char*>(0x00ffc468, 0x00ffbdb0)
. There is no such pair in the set, so find
returns end
.
Your code compares char *
's, which checks if they point to the same place in memory, not whether they point to identical content. You should probably use std::string
instead of char *
rather than reinventing wheels.
Here's an example of a possible comparison function you could use if you insist on doing so:
bool less(
std::pair<char *, char *> const& p1,
std::pair<char *, char *> const& p2)
{
int i = strcmp (p1.first, p2.first);
if (i < 0)
return true;
if (i > 0)
return false;
return strcmp (p1.second, p2.second) < 0;
}
If you must use std:pair<char*, char*>
as key in your map, you can use the following functor while creating the map.
struct MyCompare
{
bool operator()(std::pair<char const*, char const*> const& lhs,
std::pair<char const*, char const*> const& rhs)
{
int n1 = strcmp(lhs.first, rhs.first);
if ( n1 != 0 )
{
return n1 < 0;
}
return (strcmp(lhs.second, rhs.second) < 0);
}
};
typedef std::map<std::pair<char*,char*>, int, MyCompare> MyMap;
MyMap myMap;
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.