简体   繁体   中英

find struct as value in std::map

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!

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

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.

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