C++:哈希表封装

张开发
2026/5/13 22:51:11 15 分钟阅读
C++:哈希表封装
C 哈希表封装链地址法cpp运行#include iostream #include vector #include list #include string using namespace std; // 键值对节点 template typename K, typename V struct HashNode { K key; V value; HashNode(K k, V v) : key(k), value(v) {} }; // 哈希表封装类 template typename K, typename V class HashTable { private: vectorlistHashNodeK, V table; int capacity; // 桶数量 int size; // 元素个数 // 哈希函数简单取模 int hash(const K key) const { return hashK{}(key) % capacity; } public: // 构造函数 HashTable(int cap 10) : capacity(cap), size(0) { table.resize(capacity); } // 插入 / 更新 void put(const K key, const V value) { int idx hash(key); for (auto node : table[idx]) { if (node.key key) { node.value value; return; } } table[idx].emplace_back(key, value); size; } // 查找 bool get(const K key, V outValue) const { int idx hash(key); for (const auto node : table[idx]) { if (node.key key) { outValue node.value; return true; } } return false; } // 删除 bool remove(const K key) { int idx hash(key); auto list table[idx]; for (auto it list.begin(); it ! list.end(); it) { if (it-key key) { list.erase(it); size--; return true; } } return false; } // 是否包含 key bool contains(const K key) const { V tmp; return get(key, tmp); } // 获取大小 int getSize() const { return size; } // 是否为空 bool isEmpty() const { return size 0; } }; // 测试 int main() { HashTablestring, int ht; ht.put(apple, 10); ht.put(banana, 20); ht.put(orange, 30); int val; if (ht.get(banana, val)) { cout banana: val endl; } ht.remove(apple); cout size: ht.getSize() endl; return 0; }核心特点精简说明模板实现支持任意可哈希 key 类型int、string 等使用链地址法解决哈希冲突实现核心接口put(key, value)插入 / 更新get(key, outVal)查找remove(key)删除contains(key)判断存在结构轻量、无依赖、可直接编译运行适合学习底层原理也可用于简单项目

更多文章