对于unordered_map而言,当我们插入的时候,需要哈希函数的函数对象对key进行hash,又要利用等比函数的函数对象确保插入的键值对没有重复。

    如果要将自定义类型作为unordered_map的键值,需如下两个步骤:

    • 定义哈希函数的函数对象;
    • 定义等比函数的函数对象或者在自定义类里重载operator==()。
    1. #include <iostream>
    2. #include <string>
    3. #include <unordered_map>
    4. #include <functional>
    5. using namespace std;
    6. class Person{
    7. public:
    8. string name;
    9. int age;
    10. Person(string n, int a){
    11. name = n;
    12. age = a;
    13. }
    14. //在自定义类里重载operator==()
    15. bool operator==(const Person & p) const
    16. {
    17. return name == p.name && age == p.age;
    18. }
    19. };
    20. //利用重载operator()的类,将哈希函数打包成可以直接调用的类
    21. struct hash_name{
    22. size_t operator()(const Person & p) const{
    23. return hash<string>()(p.name) ^ hash<int>()(p.age);
    24. }
    25. };
    26. int main(int argc, char* argv[]){
    27. unordered_map<Person, int, hash_name> ids;
    28. ids[Person("Mark", 17)] = 40561;
    29. ids[Person("Andrew",16)] = 40562;
    30. for ( auto ii = ids.begin() ; ii != ids.end() ; ii++ )
    31. cout << ii->first.name
    32. << " " << ii->first.age
    33. << " : " << ii->second
    34. << endl;
    35. return 0;
    36. }

    参考自:https://blog.csdn.net/y109y/article/details/82669620 的方法2