比较地图中的结构体。

huangapple go评论72阅读模式
英文:

Compare a struct in a map

问题

You can use the find function with a custom struct as the key in a std::map. However, to do so, you need to ensure that your custom struct has a comparison operator defined or provide a custom comparator, which you've already done in your code. So, yes, you can adapt it to your TechId struct with the our_cmp comparator you've defined.

英文:

I want to map a struct(key) to an int(value). Then I want to find a value given a key (struct).

typedef struct {
  int  a, b; 
} TechId;  

struct our_cmp {
  bool operator() ( TechId a, TechId b ) const
  { return std::make_pair(a.a,a.b) > std::make_pair(b.a, b.b) ; }

};

int main() {
std::map<TechId, int, our_cmp> mymap;

TechId x;

if(mymap.find(x)) {
  printf("found");
}

}

There is a find function but I guess it is only for string/ints etc? Is there a possibility to adapt it to my struct?

答案1

得分: 4

你需要检查find返回的迭代器与地图的end()迭代器是否相等。如果它们不相等,那么你搜索的元素已经找到:

if (mymap.find(x) != mymap.end()) {
    printf("found");
}

自C++20起,你也可以使用contains成员函数来完成相同的操作:

if (mymap.contains(x)) {
    printf("found");
}
英文:

You need to check the iterator returned by find with the end() iterator of the map. If they are not equal, the element you searched for was found:

if (mymap.find(x) != mymap.end()) {
    printf("found");
}

Since C++20, you could also use the contains member function to do the same thing:

if (mymap.contains(x)) {
    printf("found");
}

huangapple
  • 本文由 发表于 2023年7月6日 18:32:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定