hash_map哈希映照容器的实现(template)

本文介绍了hash_map的数据结构原理及其与map的区别。hash_map使用hash_set存储结构来实现映射功能,提供近似O(1)的时间复杂度进行元素检索。文章还提供了hash_map的一个实现模板,帮助读者理解其内部工作流程。

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

hash_map,顾名思义,就是利用hash_set存储结构的写map映照容器,普通的map用的是红黑树存储结构写的。元素的检索时间对比,hash_set近似为O(1),红黑树为O(logn)。Hash_map的空间开销要比map 的空间开销大,尤其是我用数组模拟指针写的hash_map。

所以,如果有必要采取映射结构的时候,能用hash_map就别用map。

需要注意的是,hash_map遍历出来的元素不是有序的。

Hash_map和普通hash_set相比的话,hash_map比hash_set多了一张value表,也就是映射表。

下面是hash_map的模板,和hash_set的模板差不多。

template<class KeyType,int MaxHash>
struct HashFunction
{
    int operator()(const KeyType& key)
    {
        int h=key%MaxHash;
        if (h<0) h+=MaxHash;
        return h;
    }
};

template<class KeyType,class ValueType,int KeyContain,int MaxHash,class HashFun=HashFunction<KeyType,MaxHash> >
class HashMap
{
public:
    HashMap():hashfun(){Clear();}
    ValueType& operator[](const KeyType& key)
    {
        int h=hashfun(key);
        int pos=head[h];
        for(;pos!=0;pos=next[pos])
        {
            if(keys[pos]==key)
                return values[pos];
        }
        next[++top]=head[h];
        head[h]=top;
        keys[top]=key;
        values[top]=ValueType();//初始化
        ++sz;
        return values[top];
    }
    void Clear()
    {
        memset(head,0,sizeof(head));
        memset(next,0,(top+1)*sizeof(int));
        top=0;
        sz=0;
    }
    unsigned int size() const {return sz;}

private:
    unsigned int sz;
    HashFun hashfun;
    int head[MaxHash];
    int next[KeyContain];
    KeyType keys[KeyContain];
    ValueType values[KeyContain];
    int top;
};

from C小加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值