linux cc++ map使用结构体所为key怎么实现
在C/C++中,可以使用函数指针作为map中的键。可以使用以下步骤实现将结构体作为map的键:
- 定义一个结构体作为
map的键,例如struct Key { ... }; - 实现一个比较函数,用于比较两个键的大小,例如
bool compareKeys(const Key& key1, const Key& key2) { ... } - 声明一个
map,使用compareKeys作为键的比较函数,例如std::map<Key, ValueType, bool(*)(const Key&, const Key&)> myMap(compareKeys); - 可以使用
myMap进行插入、查找和删除操作。
下面是一个完整的示例代码:
#include <iostream>
#include <map>
// 定义结构体作为map的键
struct Key {
int x;
int y;
};
// 定义比较函数
bool compareKeys(const Key& key1, const Key& key2) {
if (key1.x < key2.x) {
return true;
} else if (key1.x == key2.x) {
return key1.y < key2.y;
} else {
return false;
}
}
int main() {
// 声明map,使用compareKeys作为键的比较函数
std::map<Key, int, bool(*)(const Key&, const Key&)> myMap(compareKeys);
// 插入键值对
myMap[Key{1, 2}] = 10;
myMap[Key{3, 4}] = 20;
// 查找键值对
Key searchKey{3, 4};
auto it = myMap.find(searchKey);
if (it != myMap.end()) {
std::cout << "Value found: " << it->second << std::endl;
} else {
std::cout << "Value not found." << std::endl;
}
// 删除键值对
myMap.erase(Key{1, 2});
return 0;
}
在上面的示例代码中,Key结构体表示键,compareKeys函数用于比较两个键的大小。std::map的声明中,第三个模板参数是一个函数指针类型,指定了键的比较函数。在main函数中,首先使用compareKeys函数初始化了myMap,然后可以使用myMap进行插入、查找和删除操作。
原文地址: https://www.cveoy.top/t/topic/i4JO 著作权归作者所有。请勿转载和采集!