#include <map>
#include <unordered_map>
class mapStruct
{
int x;
public:
bool operator<(mapStruct b) const { return this->x < b.x; }
// bool operator==(const myStruct b) { return this->x == b.x; }
};
class unordermapStruct
{
int x;
public:
bool operator<(unordermapStruct b) const { return this->x < b.x; }
// bool operator==(unordermapStruct b) const { return this->x == b.x; }
};
template <>
class std::hash<unordermapStruct>
{
std::size_t operator()(const unordermapStruct &a) const
{
return 1;
}
};
int main()
{
mapStruct a;
unordermapStruct b;
std::map<mapStruct, int> myMap;
std::unordered_map<unordermapStruct, int> myUnorderMap;
myMap[a] = 1;
return 0;
}
/**
1. map中key如果是自定义结构, 需要定义operator < 用于排序比较
2. unordered_map 中的key如果是自定义结构, 需要特例化std::hash<CustomerStruct>
* **/
unordered_map map 自定义key
最新推荐文章于 2025-03-25 11:00:59 发布
本文介绍了如何使用自定义结构作为 C++ STL 中 map 和 unordered_map 的键。对于 map, 需要定义 operator< 以进行排序;对于 unordered_map, 则需要特例化 std::hash 以实现哈希计算。
249

被折叠的 条评论
为什么被折叠?



