C++ STL中unordered_set、unordered_map之类的容器,若要使用自定义类型作为key,则需要自定义哈希函数和哈希比较函数,示例如下:
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <string>
using namespace std;
class HashFunc
{
public:
size_t operator()(const pair<int, int>& range) const noexcept
{
hash<string> hs;
return hs(to_string(range.first) + to_string(range.second));
}
};
class KeyEqual
{
public:
bool operator()(const pair<int,int> &u, const pair<int,int> &v) const
{
return (u.first == v.first) && (u.second == v.second);
}
};
int main()
{
unordered_map<pair<int, int>, int, HashFunc, KeyEqual> mp;
mp[make_pair(1, 2)] = 2;
cout << mp[make_pair(1, 2)] << endl;
if (mp.count(make_pair(3, 4)))
cout << "found key" << endl;
unordered_set<pair<int, int>, HashFunc, KeyEqual> ss;
ss.insert(make_pair(2, 3));
ss.insert(make_pair(1, 5));
ss.insert(make_pair(2, 3));
cout << ss.size() << endl;
return 0;
}