使用拉链法解决hash 冲突。
对外提供insert find remove接口
#include <iostream>
#include <vector>
#include <list>
#include <string>
template<typename Key, typename Value>
class HashTable {
public:
HashTable(size_t size) : buckets_(size) {}
void insert(const Key& key, const Value& value) {
size_t index = hash(key);
for (auto& node : buckets_[index]) {
if (node.first == key) {
node.second = value;
return;
}
}
buckets_[index].emplace_back(key, value);
}
bool find(const Key& key, Value& value) const {
size_t index = hash(key);
for (const auto& node : buckets_[index]) {
if (node.first == key) {
value = node.second;
return true;
}
}
return false;
}
void remove(const Key& key) {
size_t index = hash(key);
auto& bucket = buckets_[index];
for (auto iter = bucket.begin(); iter != bucket.end(); iter++) {
if (iter->first == key) {
bucket.erase(iter);
return;
}
}
}
private:
using Node = std::pair<Key, Value>;
using NodeList = std::list<Node>;
std::vector<NodeList> buckets_;
size_t hash(const Key& key) const {
return std::hash<Key>()(key) % buckets_.size();
}
};
int main() {
HashTable<std::string, int> table(10);
table.insert("apple", 1);
table.insert("banana", 2);
table.insert("cherry", 3);
int value;
if (table.find("banana", value)) {
std::cout << "banana:" << value << std::endl;
}
table.remove("banana");
if (table.find("banana", value)) {
std::cout << "banana: " << value << std::endl;
} else {
std::cout << "banana not found" << std::endl;
}
return 0;
}
banana:2
banana not found