请用C++简单实现哈希表,冲突采用链地址法,使用头文件list
时间: 2024-10-11 11:12:06 浏览: 35
在C++中,我们可以使用`std::unordered_map`实现哈希表,它内部已经采用了开放寻址法或链地址法处理冲突。但是如果你想手动实现简单的哈希表(散列表),这里是一个基于链地址法的例子,使用了`std::list`作为链表:
```cpp
#include <iostream>
#include <list>
// 哈希函数示例,你可以根据需要替换为更复杂的哈希算法
unsigned int hash_function(const std::string& key) {
return std::hash<std::string>{}(key);
}
// 哈希表节点结构体
struct Node {
std::string key;
std::string value;
Node* next; // 链接指针
Node(const std::string& k, const std::string& v) : key(k), value(v), next(nullptr) {}
};
class HashTable {
private:
unsigned int size;
std::list<Node*> buckets;
public:
HashTable(unsigned int s) : size(s) {
for (unsigned int i = 0; i < size; ++i)
buckets.push_back(nullptr); // 初始化所有桶为NULL
}
void insert(const std::string& key, const std::string& value) {
unsigned int index = hash_function(key) % size;
Node* newNode = new Node(key, value);
if (!buckets[index]) { // 如果当前桶为空,直接插入
buckets[index] = newNode;
} else {
for (Node* node = buckets[index]; node; node = node->next) {
if (node->key == key) { // 如果找到冲突键,则更新值
node->value = value;
break;
}
if (node->next == nullptr) { // 如果链表结束,插入新节点
node->next = newNode;
break;
}
}
}
}
std::string get(const std::string& key) const {
unsigned int index = hash_function(key) % size;
for (Node* node = buckets[index]; node; node = node->next) {
if (node->key == key)
return node->value;
}
throw std::runtime_error("Key not found");
}
~HashTable() {
for (auto bucket : buckets) {
while (bucket) {
Node* temp = bucket;
bucket = bucket->next;
delete temp;
}
}
}
};
int main() {
HashTable table(10);
table.insert("apple", "fruit");
table.insert("code", "programming");
try {
std::cout << "Value of 'apple': " << table.get("apple") << std::endl;
std::cout << "Value of 'banana': " << table.get("banana") << std::endl; // 这里会抛出异常,因为'banana'不存在
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文
相关推荐


















