概述: 无聊的时候学一下。
完整代码:
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
template<typename K, typename V>
class HashMap {
public:
HashMap(size_t capacity = 10) : capacity_(capacity), size_(0) {
table_.resize(capacity_);
}
void put(const K& key, const V& value) {
size_t index = hash(key) % capacity_;
for (auto& pair : table_[index]) {
if (pair.first == key) {
pair.second = value;
return;
}
}
table_[index].emplace_back(key, value);
++size_;
}
V get(const K& key) {
size_t index = hash(key) % capacity_;
for (auto& pair : table_[index]) {
if (pair.first == key) {
return pair.second;
}
}
throw std::runtime_error("Key not found");
}
bool remove(const K& key) {
size_t