hashmap的C++实现

本文介绍了使用C++按照HashMap的基本原理实现其简单功能,强调了在C++11标准库中已有unordered_set、unordered_multiset、unordered_map和unordered_multimap等基于hashtable的容器。在自定义实现中,key需唯一,可通过[]操作修改value,但不能添加value。由于C++编译器特性,头文件和实现代码需放在一起,并需提供key的hash函数对象和equal函数对象。

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

按照hashmap的基本原理用C++实现了简单的基本功能,复杂的实现参考C++库的源码,C++最新的标准库里已经有以下四种基于hashtable的容器:

unordered_set (C++11) unordered_multiset (C++11) unordered_map (C++11) unordered_multimap (C++11)。

/*
 * HashMap.h
 * Author: luxiaoxun
 */

#ifndef HASHMAP_H_
#define HASHMAP_H_

#include <iostream>
using namespace std;

//List all the integer number no less than 57 total number is 28
//And each number is about half of its next number
static int prime[28] =
{
    57,        97,         193,        389,        769,
    1543,      3079,       6151,       12289,      24593,
    49157,     98317,      196613,     393241,     786433,
    1572869,   3145739,    6291469,    12582917,   25165843,
    50331653,  100663319,  201326611,  402653189,  805306457,
    1610612741
};

class HashMapUtil
{
public:
    static int find_NextPrimeNumber(int current)
    {
        //Find the next prime number by searching in the prime number list
        int i = 0;
        for( ; i < 28 ; i++ )
            if(current < prime[i])
                break;
        return prime[i];     //return the next larger prime.
    }
};

template <class Key, class Value, class HashFunc, class EqualKey>
class HashMap
{
private:
    template <class _Key, class _Value>
    class KeyNode
    {
        public:
        _Value  value;      //Store the value
        _Key    key;        //Store the keyword
        int    used;
        //if the type of Value/Key is your own class, make sure they can handle copy constructor and operator =
        KeyNode():used(0){}
        KeyNode(const KeyNode & kn)
        {
            value = kn.value;
            key = kn.key;
            used = kn.used;
        }
        KeyNode & operator=(const KeyNode & k
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值