Pracka Pracka - 1 month ago 24
C++ Question

find struct as value in std::map

I am trying to use

to find a value, which is a custom struct, in the dictionary. The following code will not compile

typedef struct myStruct
int x;
int y;

MyStruct instace;
instace.x = 0;
instace.y = 1;

map<unsigned int, myStruct> myMap;
myMap[0] = instace;
if(myMap.count(instace) == 1)
//do something

and this is the error I get

no instance of overloaded function "std::map<_Kty, _Ty, _Pr, _Alloc>::count
[with _Kty=unsigned int, _Ty=myStruct, _Pr=std::less<unsigned int>,
_Alloc=std::allocator<std::pair<const unsigned int, myStruct>>]" matches the
argument list

I think the compiler does not know how to compare my struct. The third argument in the declaration of a map takes a compare function, I tried to create a compare function and pass it to the third argument in declaration like the following

struct comparer
bool operator()(MyStruct const& Left, MyStruct const& Right) const {
return (Left.x == Right.x && Left.y == Right.y);

map<unsigned int, myStruct, comparer> myMap;

but when I do
, I get similar error.

I have searched google using every possible way I could describe the problem, but I did not find the answer. Can someone tell me how to solve this problem?

Answer Source

Looking at std::map::count, count takes the key and return the number of elements associated with that key. That means that your code should be:

if(myMap.count(0) == 1)  // for key == 0