对于unordered_map而言,当我们插入
如果要将自定义类型作为unordered_map的键值,需如下两个步骤:
- 定义哈希函数的函数对象;
- 定义等比函数的函数对象或者在自定义类里重载operator==()。
#include <iostream>
#include <string>
#include <unordered_map>
#include <functional>
using namespace std;
class Person{
public:
string name;
int age;
Person(string n, int a){
name = n;
age = a;
}
//在自定义类里重载operator==()
bool operator==(const Person & p) const
{
return name == p.name && age == p.age;
}
};
//利用重载operator()的类,将哈希函数打包成可以直接调用的类
struct hash_name{
size_t operator()(const Person & p) const{
return hash<string>()(p.name) ^ hash<int>()(p.age);
}
};
int main(int argc, char* argv[]){
unordered_map<Person, int, hash_name> ids;
ids[Person("Mark", 17)] = 40561;
ids[Person("Andrew",16)] = 40562;
for ( auto ii = ids.begin() ; ii != ids.end() ; ii++ )
cout << ii->first.name
<< " " << ii->first.age
<< " : " << ii->second
<< endl;
return 0;
}
参考自:https://blog.csdn.net/y109y/article/details/82669620 的方法2