首页 > 编程语言 >c++ 实现hashmap

c++ 实现hashmap

时间:2022-08-17 21:58:22浏览次数:76  
标签:node const hashmap 实现 HashNode c++ key hash HashMap

由于hashmap不是c++ stl中标准实现,这样在跨平台使用时就可能会出现问题,于是想到自己实现一个hashmap

hash算法使用开链法解决hash冲突,主要实现了添加,删除,查找几个方法

头文件如下hashmap.h

#ifndef _HASHMAP_H_
#define _HASHMAP_H_



template<class Key, class Value>
class HashNode
{
public:
    Key    _key;
    Value  _value;
    HashNode *next;

    HashNode(Key key, Value value)
    {
        _key = key;
        _value = value;
        next = NULL;
    }
    ~HashNode()
    {

    }
    HashNode& operator=(const HashNode& node)
    {
        key = node.key;
        value = node.key;
        next = node.next;
        return *this;
    }
};

template <class Key, class Value, class HashFunc, class EqualKey>
class HashMap
{
public:
    HashMap(int size);
    ~HashMap();
    bool insert(const Key& key, const Value& value);
    bool del(const Key& key);
    Value& find(const Key& key);
    Value& operator [](const Key& key);

private:
    HashFunc hash;
    EqualKey equal;
    HashNode<Key, Value> **table;
    unsigned int _size;
    Value ValueNULL;
};


template <class Key, class Value, class HashFunc, class EqualKey>
HashMap<Key, Value, HashFunc, EqualKey>::HashMap(int size) : _size(size)
{
    hash = HashFunc();
    equal = EqualKey();
    table = new HashNode<Key, Value>*[_size];
    for (unsigned i = 0; i < _size; i++)
        table[i] = NULL;
}



template <class Key, class Value, class HashFunc, class EqualKey>
HashMap<Key, Value, HashFunc, EqualKey>::~HashMap()
{
    for (unsigned i = 0; i < _size; i++)
    {
        HashNode<Key, Value> *currentNode = table[i];
        while (currentNode)
        {
            HashNode<Key, Value> *temp = currentNode;
            currentNode = currentNode->next;
            delete temp;
        }
    }
    delete table;
}


template <class Key, class Value, class HashFunc, class EqualKey>
bool HashMap<Key, Value, HashFunc, EqualKey>::insert(const Key& key, const Value& value)
{
    int index = hash(key)%_size;
    HashNode<Key, Value> * node = new HashNode<Key, Value>(key,value);
    node->next = table[index];
    table[index] = node;
    return true;
}


template <class Key, class Value, class HashFunc, class EqualKey>
bool HashMap<Key, Value, HashFunc, EqualKey>::del(const Key& key)
{
    unsigned index = hash(key) % _size;
    HashNode<Key, Value> * node = table[index];
    HashNode<Key, Value> * prev = NULL;
    while (node)
    {
        if (node->_key == key)
        {
            if (prev == NULL)
            {
                table[index] = node->next;
            }
            else
            {
                prev->next = node->next;
            }
            delete node;
            return true;
        }
        prev = node;
        node = node->next;
    }
    return false;
}

template <class Key, class Value, class HashFunc, class EqualKey>
Value& HashMap<Key, Value, HashFunc, EqualKey>::find(const Key& key)
{
    unsigned  index = hash(key) % _size;
    if (table[index] == NULL)
        return ValueNULL;
    else
    {
        HashNode<Key, Value> * node = table[index];
        while (node)
        {
            if (node->_key == key)
                return node->_value;
            node = node->next;
        }
    }
}


template <class Key, class Value, class HashFunc, class EqualKey>
Value& HashMap<Key, Value, HashFunc, EqualKey>::operator [](const Key& key)
{
    return find(key);
}


#endif

测试代码

//首先要定义hash函数与比较函数
class HashFunc
{
public:
    int operator()(const string & key )
    {
        int hash = 0;
        for(int i = 0; i < key.length(); ++i)
        {
            hash = hash << 7 ^ key[i];
        }
        return (hash & 0x7FFFFFFF);
    }
};


class EqualKey
{
public:
    bool operator()(const string & A, const string & B)
    {
        if (A.compare(B) == 0)
            return true;
        else
            return false;
    }
};

测试用例
int main()
{
    HashMap<string, string, HashFunc, EqualKey> hashmap(100);

    hashmap.insert("hello", "world");
    hashmap.insert("why", "dream");
    hashmap.insert("c++", "good");
    hashmap.insert("welcome", "haha");

    
    cout << "after insert:" << endl;
    cout << hashmap.find("welcome").c_str() << endl;
    cout << hashmap.find("c++").c_str() << endl;
    cout << hashmap["why"].c_str() << endl;
    cout << hashmap["hello"].c_str() << endl;

    if (hashmap.del("hello"))
        cout << "remove is ok" << endl;    //remove is ok
    cout << hashmap.find("hello").c_str() << endl; //not exist print NULL

    hashmap["why"] = "love";
    cout << hashmap["why"].c_str() << endl;
    return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家

标签:node,const,hashmap,实现,HashNode,c++,key,hash,HashMap
From: https://www.cnblogs.com/myhomepages/p/16596885.html

相关文章

  • C++primer练习14.26
    练习14.26为你的String类定义下标运算符char&operator[](size_td){returnelements[d];}constchar&operator[](size_td)const......
  • CPU中实现了哪些寄存器类型?
    1)程序计数器(ProgramCounter)(PC):程序计数器是一个寄存器,用来保存当前正在执行的指令的地址。2)指令寄存器(InstructionRegister )(IR):指令寄存器是保存当前正在执行的指令的寄......
  • 技术专家说 | 如何基于 Spark 和 Z-Order 实现企业级离线数仓降本提效?
    【点击了解更多大数据知识】市场的变幻,政策的完善,技术的革新……种种因素让我们面对太多的挑战,这仍需我们不断探索、克服。今年,网易数帆将持续推出新栏目「金融专家说」......
  • 【CV源码项目实现】darknet中network的实现过程
     darknet的网络结构使用network结构体进行保存,network的构建过程主要包括以下几个函数:load_network(src/networks.c)----->parse_network_cfg(src/parser.c) --->ma......
  • 【CV项目源码实现】Floating point exception (core dumped)
    前言cmd./darknetdetectordemocfg/tfl.datacfg/yolov3-tiny-tfl.cfgbackup/yolov3-tiny-tfl_500000.weightsdata/tfl.avierrorFloatingpointexception(cor......
  • redis实现消息队列的几种方式及其优劣
    redis实现消息队列的几种方式及其优劣衡与墨已于2022-04-2720:46:32修改5617收藏24分类专栏:redis精华文章标签:redispub-substream消息队列版权redis同时被......
  • js数据结构与算法-队列的实现
    和栈的实现相似,但是这里使用对象的方式,对象的key是数字的实现,类似数组。/***队列*/classQueue{#count=0;//队列最大数量#lowestCount=0;//目前......
  • C/C++ 如何拷贝一个wchar_t类型的字符串
    1Dothis,23wchar_tclone[260];45wcscpy(clone,szPath);67Or,ifyouwanttoallocatememoryyourself,89wchar_t*clone=newwchar_t[wc......
  • C++ 起别名
    可以基于typedef、using等关键词实现typedef std::vector<int>intvec;using intvec =std::vector<int>; //这两个写法是等价的另一个例子,函数指针:typedefvoid(*......
  • innodb是如何实现事务的
    innodb通过buffer pool,logBuffer,RedoLog,UndoLog来实现事务的,以update语句举例:innodb在收到一个update语句后,会先根据条件找到数据所在的页,并将该页缓......