map 的key是结构体value 是int 怎么实现增、删查
要实现对结构体作为key,int作为value的map的增、删、查操作,可以按照以下步骤进行:
- 定义结构体类型,并确保它是可比较的(实现
==和<运算符)。
struct MyStruct {
int field1;
int field2;
// 其他字段和方法...
// 实现比较运算符
bool operator==(const MyStruct& other) const {
return field1 == other.field1 && field2 == other.field2;
}
bool operator<(const MyStruct& other) const {
if (field1 != other.field1) {
return field1 < other.field1;
}
return field2 < other.field2;
}
};
- 创建map对象,并进行增、删、查操作。
#include <iostream>
#include <map>
int main() {
std::map<MyStruct, int> myMap;
// 增加元素
MyStruct key1 {1, 2};
int value1 = 10;
myMap[key1] = value1;
// 删除元素
myMap.erase(key1);
// 查找元素
MyStruct key2 {3, 4};
int value2 = 20;
myMap[key2] = value2;
std::map<MyStruct, int>::iterator it = myMap.find(key2);
if (it != myMap.end()) {
std::cout << "找到了,值为:" << it->second << std::endl;
} else {
std::cout << "未找到" << std::endl;
}
return 0;
}
在上面的代码中,我们首先定义了一个MyStruct结构体类型,并实现了==和<运算符,以便能够在map中进行比较和排序。
然后,我们创建了一个std::map<MyStruct, int>对象myMap,并使用[]运算符进行增加元素的操作。我们还可以使用erase()函数删除指定的key对应的元素。
最后,我们使用find()函数在map中查找指定的key,并根据返回的迭代器判断是否找到了对应的元素。如果找到了,我们可以通过迭代器的second成员访问对应的value。
原文地址: http://www.cveoy.top/t/topic/i1Yw 著作权归作者所有。请勿转载和采集!