在C++中实现Hashtable可以使用标准库中的unordered_map或者自己实现一个Hashtable类。以下是一个简单的自定义Hashtable类的实现示例:
#include <iostream>#include <vector>#include <list>class Hashtable {private: static const int TABLE_SIZE = 10; std::vector<std::list<std::pair<int, int>>> table; int hashFunction(int key) { return key % TABLE_SIZE; }public: Hashtable() { table.resize(TABLE_SIZE); } void insert(int key, int value) { int index = hashFunction(key); for (auto& pair : table[index]) { if (pair.first == key) { pair.second = value; return; } } table[index].push_back({key, value}); } void remove(int key) { int index = hashFunction(key); table[index].remove_if([key](std::pair<int, int> pair) { return pair.first == key; }); } int get(int key) { int index = hashFunction(key); for (auto& pair : table[index]) { if (pair.first == key) { return pair.second; } } return -1; // key not found }};int main() { Hashtable ht; ht.insert(1, 10); ht.insert(2, 20); std::cout << ht.get(1) << std::endl; // Output: 10 std::cout << ht.get(2) << std::endl; // Output: 20 ht.remove(1); std::cout << ht.get(1) << std::endl; // Output: -1 (key not found) return 0;}在这个例子中,我们使用一个vector来存储链表,每个链表存储具有相同hash值的键值对。我们实现了插入、删除和获取操作。实际上,C++标准库中的unordered_map就是使用类似的哈希表实现的。