英文:
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");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论