下面是一个简单的示例,展示如何使用C++实现一个基本的哈希表(Hash Map):
#include <iostream>
#include <vector>
#include <list>
// 定义哈希表的节点
template<typename K, typename V>
struct HashNode {
K key;
V value;
HashNode(const K& k, const V& v) : key(k), value(v) {}
};
// 哈希表类定义
template<typename K, typename V, typename Hash = std::hash<K>>
class HashMap {
public:
explicit HashMap(int size = 100) : size_(size), count_(0), table_(size) {}
// 向哈希表中插入键值对
void insert(const K& key, const V& value) {
int index = hashFunction(key);
for (auto it = table_[index].begin(); it != table_[index].end(); ++it) {
if ((*it).key == key) {
(*it).value = value; // 如果键已经存在,则更新其对应的值
return;
}
}
table_[index].push_back(HashNode<K, V>(key, value));
count_++;
}
// 根据键查找对应的值
bool find(const K& key, V& value) {
int index = hashFunction(key);
for (auto it = table_[index].begin(); it != table_[index].end(); ++it) {
if ((*it).key == key) {
value = (*it).value;
return true; // 找到键,并将对应的值赋给参数value
}
}
return false; // 未找到键
}
// 从哈希表中删除指定的键值对
void erase(const K& key) {
int index = hashFunction(key);
for (auto it = table_[index].begin(); it != table_[index].end(); ++it) {
if ((*it).key == key) {
table_[index].erase(it); // 删除节点
count_--;
return;
}
}
}
private:
std::vector<std::list<HashNode<K, V>>> table_; // 哈希表存储数据的数组,每个元素是一个链表
int size_; // 哈希表的大小(桶数量)
int count_; // 当前存储在哈希表中的键值对数量
Hash hashFunction; // 哈希函数对象
// 根据键计算哈希值,并映射到合适的桶索引
int hashFunction(const K& key) {
return hashFunction(key) % size_;
}
};
int main() {
HashMap<std::string, int> hashMap;
hashMap.insert("apple", 10);
hashMap.insert("banana", 20);
int value = 0;
if (hashMap.find("apple", value)) {
std::cout << "Value of apple: " << value << std::endl;
hashMap.erase("apple");
if (!hashMap.find("apple", value)) {
std::cout << "Apple is not found in the hashmap." << std::endl;
}
}
return 0;
}
这只是一个简单的示例,实际上哈希表的实现会更复杂和完善。这个示例使用了一个vector来存储桶,并且每个桶都是一个链表,用于解决哈希冲突。你可以根据自己的需求和场景对其进行进一步的扩展和优化。
内容由零声教学AI助手提供,问题来源于学员提问




