如何在C++中实现Hashtable

   2024-10-06 2310
核心提示:在C++中实现Hashtable可以使用标准库中的unordered_map或者自己实现一个Hashtable类。以下是一个简单的自定义Hashtable类的实现

在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就是使用类似的哈希表实现的。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号