设计一个自定义的C++哈希表需要考虑以下几个关键点:
下面是一个简单的自定义C++哈希表设计示例,使用了链地址法来解决冲突,并且支持动态扩容:
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
template <typename Key, typename Value>
class HashTable {
private:
struct Entry {
Key key;
Value value;
bool occupied;
Entry() : occupied(false) {}
};
std::vector<std::list<Entry>> table;
size_t size;
size_t capacity;
float loadFactorThreshold;
size_t hash(const Key& key) const {
return std::hash<Key>{}(key) % capacity;
}
void rehash(size_t newCapacity) {
std::vector<std::list<Entry>> newTable(newCapacity);
for (const auto& bucket : table) {
for (const auto& entry : bucket) {
if (entry.occupied) {
size_t newIndex = std::hash<Key>{}(entry.key) % newCapacity;
newTable[newIndex].push_back(entry);
}
}
}
table = std::move(newTable);
capacity = newCapacity;
}
public:
HashTable(size_t initialCapacity = 10, float loadFactorThreshold = 0.75)
: size(0), capacity(initialCapacity), loadFactorThreshold(loadFactorThreshold) {
table.resize(capacity);
}
void insert(const Key& key, const Value& value) {
if (static_cast<float>(size) / capacity >= loadFactorThreshold) {
rehash(capacity * 2);
}
size_t index = hash(key);
for (auto& entry : table[index]) {
if (entry.key == key) {
entry.value = value;
return;
}
}
table[index].push_back({key, value, true});
++size;
}
bool remove(const Key& key) {
size_t index = hash(key);
for (auto it = table[index].begin(); it != table[index].end(); ++it) {
if (it->key == key) {
table[index].erase(it);
--size;
return true;
}
}
return false;
}
bool find(const Key& key, Value& value) const {
size_t index = hash(key);
for (const auto& entry : table[index]) {
if (entry.key == key) {
value = entry.value;
return true;
}
}
return false;
}
size_t getSize() const {
return size;
}
size_t getCapacity() const {
return capacity;
}
};
int main() {
HashTable<int, std::string> ht;
ht.insert(1, "one");
ht.insert(11, "eleven");
ht.insert(21, "twenty-one");
std::string value;
if (ht.find(11, value)) {
std::cout << "Found: " << value << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
ht.remove(11);
if (ht.find(11, value)) {
std::cout << "Found: " << value << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
std::hash<Key>
来生成键的哈希值。std::list<Entry>
。loadFactorThreshold
时,将容量加倍。std::vector
来管理桶,自动处理内存分配和释放。这个示例是一个基础的哈希表实现,可以根据具体需求进行扩展和优化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。