Home:ALL Converter>find struct as value in std::map

find struct as value in std::map

Ask Time:2017-09-25T09:16:46         Author:Pracka

Json Formatter

I am trying to use std::map::count() 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;

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 myMap.count(), 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? Thanks!

Author:Pracka,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46396364/find-struct-as-value-in-stdmap
yy