std::map键 自定义类型
时间: 2024-01-04 17:19:47 浏览: 23
可以使用自定义类型作为std::map的键。只要自定义类型定义了比较运算符(<),就可以作为std::map的键类型。
下面是一个示例,演示了如何使用自定义类型作为std::map的键:
```cpp
#include <iostream>
#include <map>
// 自定义类型
class MyType {
public:
int value;
// 构造函数
MyType(int v) : value(v) {}
// 重载比较运算符
bool operator<(const MyType& other) const {
return value < other.value;
}
};
int main() {
// 使用自定义类型作为std::map的键
std::map<MyType, std::string> myMap;
// 插入键值对
myMap[MyType(1)] = "One";
myMap[MyType(2)] = "Two";
myMap[MyType(3)] = "Three";
// 遍历输出
for (const auto& pair : myMap) {
std::cout << pair.first.value << ": " << pair.second << std::endl;
}
return 0;
}
```
输出结果:
```
1: One
2: Two
3: Three
```