简体   繁体   English

在std :: map中找到结构作为值

[英]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. 我正在尝试使用std::map::count()在字典中查找一个值,这是一个自定义结构。 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 映射声明中的第三个参数采用了compare函数,我尝试创建一个compare函数并将其传递给声明中的第三个参数,如下所示

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. 但是当我执行myMap.count() ,出现类似的错误。

I have searched google using every possible way I could describe the problem, but I did not find the answer. 我已经用我能描述问题的所有可能方式搜索了google,但没有找到答案。 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. 查看std :: map :: count ,count获取键并返回与该键关联的元素数。 That means that your code should be: 这意味着您的代码应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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