MST

星途 面试题库

面试题:C++ 自定义哈希函数在哈希表中的应用

假设你有一个自定义的类MyClass,包含多个成员变量。请编写一个C++哈希函数,用于将MyClass对象作为哈希表的键,并阐述如何在哈希表中使用这个自定义哈希函数。
19.0万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

1. 编写哈希函数

#include <iostream>
#include <unordered_map>
#include <functional>

class MyClass {
public:
    int id;
    std::string name;
    // 假设还有其他成员变量

    MyClass(int id, const std::string& name) : id(id), name(name) {}
};

namespace std {
    template<>
    struct hash<MyClass> {
        std::size_t operator()(const MyClass& obj) const {
            using std::hash;
            using std::string;

            // 结合多个成员变量生成哈希值
            return hash<int>()(obj.id) ^ hash<string>()(obj.name);
        }
    };
}

2. 在哈希表中使用自定义哈希函数

int main() {
    std::unordered_map<MyClass, int> myMap;

    MyClass obj1(1, "Alice");
    MyClass obj2(2, "Bob");

    myMap[obj1] = 100;
    myMap[obj2] = 200;

    for (const auto& pair : myMap) {
        std::cout << "Key: id = " << pair.first.id << ", name = " << pair.first.name
                  << ", Value = " << pair.second << std::endl;
    }

    return 0;
}

在上述代码中:

  1. 首先定义了MyClass类,包含idname成员变量。
  2. 然后在std命名空间中特化了hash<MyClass>模板,实现了自定义的哈希函数,通过^(异或)操作将idname的哈希值结合起来。
  3. main函数中,创建了std::unordered_map并使用MyClass作为键,展示了如何在哈希表中使用自定义哈希函数。