C++简单实现hash_table

该文章展示了一个用C++实现的哈希表类,利用拉链法处理哈希冲突。类提供了插入、查找和删除操作,内部使用了std::vector和std::list存储数据。示例代码中创建了一个哈希表,并进行了插入、查找和删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用拉链法解决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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾牙慧者

欢迎请作者喝奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值