C++实现简单的泛型Hash Map

#include<vector>
#include<list>
#include<string>
#include"iostream"

using namespace std;

class IntHash
{
public:
    int operator()(const int &value) { return value; }
};
class IntCmp
{
public:
    int operator()(const int &a, const int &b) { return a==b; }
};

template<class _Key,class _Value, class _HashFun, class _Cmp>
class hashMap
{
    typedef pair<_Key, _Value> HashPair; //哈希键值对
    typedef list<HashPair> HashList; //哈希链表(处理冲突)
    typedef vector<HashList> HashTable; //哈希表

public:
    hashMap(int size):m_size(size)
    {
        hash_table.resize(size);
    }
    void add(const _Key &key, const _Value &value)
    {
        int index = hashFun(key) % m_size;

        HashList &list = hash_table[index];

        list.push_back(pair<_Key, _Value>(key, value));
    }
    _Value find(const _Key &key)
    {
        int index = hashFun(key) % m_size;

        HashList &list = hash_table[index];

        auto it = list.begin();

        while (it != list.end())
        {
            if (hashCmp(it->first, key))
            {
                return it->second;
            }

            it++;
        }

        return NULL;
    }

private:
    int m_size;
    HashTable hash_table;

    _HashFun hashFun;
    _Cmp hashCmp;
};

int main()
{
    hashMap<int, string, IntHash, IntCmp> map(100);

    map.add(9527, "9527");
    map.add(135, "135");
    map.add(2, "2");
    map.add(567, "567");
    map.add(888, "888");
    map.add(3669, "3669");

    cout << map.find(9527) << endl;
    cout << map.find(567) << endl;
}

一个简单的泛型hashmap的实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值