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

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

头文件如下hashmap.h

  1. #ifndef _HASHMAP_H_
  2. #define _HASHMAP_H_
  3.  
  4. template<class Key, class Value>
  5. class HashNode
  6. {
  7. public:
  8. Key _key;
  9. Value _value;
  10. HashNode *next;
  11.  
  12. HashNode(Key key, Value value)
  13. {
  14. _key = key;
  15. _value = value;
  16. next = NULL;
  17. }
  18. ~HashNode()
  19. {
  20.  
  21. }
  22. HashNode& operator=(const HashNode& node)
  23. {
  24. _key = node._key;
  25. _value = node._value;
  26. next = node.next;
  27. return *this;
  28. }
  29. };
  30.  
  31. template <class Key, class Value, class HashFunc, class EqualKey>
  32. class HashMap
  33. {
  34. public:
  35. HashMap(int size);
  36. ~HashMap();
  37. bool insert(const Key& key, const Value& value);
  38. bool del(const Key& key);
  39. Value& find(const Key& key);
  40. Value& operator [](const Key& key);
  41.  
  42. private:
  43. HashFunc hash;
  44. EqualKey equal;
  45. HashNode<Key, Value> **table;
  46. unsigned int _size;
  47. Value ValueNULL;
  48. };
  49.  
  50. template <class Key, class Value, class HashFunc, class EqualKey>
  51. HashMap<Key, Value, HashFunc, EqualKey>::HashMap(int size) : _size(size),hash(),equal()
  52. {
  53. table = new HashNode<Key, Value>*[_size];
  54. for (unsigned i = ; i < _size; i++)
  55. table[i] = NULL;
  56. }
  57.  
  58. template <class Key, class Value, class HashFunc, class EqualKey>
  59. HashMap<Key, Value, HashFunc, EqualKey>::~HashMap()
  60. {
  61. for (unsigned i = ; i < _size; i++)
  62. {
  63. HashNode<Key, Value> *currentNode = table[i];
  64. while (currentNode)
  65. {
  66. HashNode<Key, Value> *temp = currentNode;
  67. currentNode = currentNode->next;
  68. delete temp;
  69. }
  70. }
  71. delete table;
  72. }
  73.  
  74. template <class Key, class Value, class HashFunc, class EqualKey>
  75. bool HashMap<Key, Value, HashFunc, EqualKey>::insert(const Key& key, const Value& value)
  76. {
  77. int index = hash(key)%_size;
  78. HashNode<Key, Value> * node = new HashNode<Key, Value>(key,value);
  79. node->next = table[index];
  80. table[index] = node;
  81. return true;
  82. }
  83.  
  84. template <class Key, class Value, class HashFunc, class EqualKey>
  85. bool HashMap<Key, Value, HashFunc, EqualKey>::del(const Key& key)
  86. {
  87. unsigned index = hash(key) % _size;
  88. HashNode<Key, Value> * node = table[index];
  89. HashNode<Key, Value> * prev = NULL;
  90. while (node)
  91. {
  92. if (node->_key == key)
  93. {
  94. if (prev == NULL)
  95. {
  96. table[index] = node->next;
  97. }
  98. else
  99. {
  100. prev->next = node->next;
  101. }
  102. delete node;
  103. return true;
  104. }
  105. prev = node;
  106. node = node->next;
  107. }
  108. return false;
  109. }
  110.  
  111. template <class Key, class Value, class HashFunc, class EqualKey>
  112. Value& HashMap<Key, Value, HashFunc, EqualKey>::find(const Key& key)
  113. {
  114. unsigned index = hash(key) % _size;
  115. if (table[index] == NULL)
  116. return ValueNULL;
  117. else
  118. {
  119. HashNode<Key, Value> * node = table[index];
  120. while (node)
  121. {
  122. if (node->_key == key)
  123. return node->_value;
  124. node = node->next;
  125. }
  126. }
  127. }
  128.  
  129. template <class Key, class Value, class HashFunc, class EqualKey>
  130. Value& HashMap<Key, Value, HashFunc, EqualKey>::operator [](const Key& key)
  131. {
  132. return find(key);
  133. }
  134.  
  135. #endif

测试代码

  1. //首先要定义hash函数与比较函数
  2. class HashFunc
  3. {
  4. public:
  5. int operator()(const string & key )
  6. {
  7. int hash = ;
  8. for(int i = ; i < key.length(); ++i)
  9. {
  10. hash = hash << ^ key[i];
  11. }
  12. return (hash & 0x7FFFFFFF);
  13. }
  14. };
  15.  
  16. class EqualKey
  17. {
  18. public:
  19. bool operator()(const string & A, const string & B)
  20. {
  21. if (A.compare(B) == )
  22. return true;
  23. else
  24. return false;
  25. }
  26. };
  27.  
  28. 测试用例
  29. int main()
  30. {
  31. HashMap<string, string, HashFunc, EqualKey> hashmap();
  32.  
  33. hashmap.insert("hello", "world");
  34. hashmap.insert("why", "dream");
  35. hashmap.insert("c++", "good");
  36. hashmap.insert("welcome", "haha");
  37.  
  38. cout << "after insert:" << endl;
  39. cout << hashmap.find("welcome").c_str() << endl;
  40. cout << hashmap.find("c++").c_str() << endl;
  41. cout << hashmap["why"].c_str() << endl;
  42. cout << hashmap["hello"].c_str() << endl;
  43.  
  44. if (hashmap.del("hello"))
  45. cout << "remove is ok" << endl; //remove is ok
  46. cout << hashmap.find("hello").c_str() << endl; //not exist print NULL
  47.  
  48. hashmap["why"] = "love";
  49. cout << hashmap["why"].c_str() << endl;
  50. return ;
  51. }

c++ 实现hashmap的更多相关文章

  1. HashMap与TreeMap源码分析

    1. 引言     在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...

  2. HashMap的工作原理

    HashMap的工作原理   HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道HashTable和HashMap之间 ...

  3. 计算机程序的思维逻辑 (40) - 剖析HashMap

    前面两节介绍了ArrayList和LinkedList,它们的一个共同特点是,查找元素的效率都比较低,都需要逐个进行比较,本节介绍HashMap,它的查找效率则要高的多,HashMap是什么?怎么用? ...

  4. Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结

    2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...

  5. 学习Redis你必须了解的数据结构——HashMap实现

    本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文链接博客园蜗牛 cnblogs.com\tdws . 首先提供一种获取hashCode的方法,是一种比较受欢迎的方式,该方法参照了一位园友的 ...

  6. HashMap与HashTable的区别

    HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...

  7. JDK1.8 HashMap 源码分析

    一.概述 以键值对的形式存储,是基于Map接口的实现,可以接收null的键值,不保证有序(比如插入顺序),存储着Entry(hash, key, value, next)对象. 二.示例 public ...

  8. HashMap 源码解析

    HashMap简介: HashMap在日常的开发中应用的非常之广泛,它是基于Hash表,实现了Map接口,以键值对(key-value)形式进行数据存储,HashMap在数据结构上使用的是数组+链表. ...

  9. java面试题——HashMap和Hashtable 的区别

    一.HashMap 和Hashtable 的区别 我们先看2个类的定义 public class Hashtable extends Dictionary implements Map, Clonea ...

  10. 再谈HashMap

    HashMap是一个高效通用的数据结构,它在每一个Java程序中都随处可见.先来介绍些基础知识.你可能也知 道,HashMap使用key的hashCode()和equals()方法来将值划分到不同的桶 ...

随机推荐

  1. MVC开发T4代码生成之一----文本模板基础

    T4文本模板 T4全写为Text Template Transformation Toolkit,是一种编程辅助工具,用来使程序代码自(懒)动(猿)生(福)成(利)的工具.MVC开发中大量使用了T4模 ...

  2. redis常用服务安装部署

    常用服务安装部署   学了前面的Linux基础,想必童鞋们是不是更感兴趣了?接下来就学习常用服务部署吧! 安装环境: centos7 + vmware + xshell 即将登场的是: mysql(m ...

  3. JAVA多线程之线程间的通信方式

    (转发) 收藏 记 周日,北京的天阳光明媚,9月,北京的秋格外肃穆透彻,望望窗外的湛蓝的天,心似透过栏杆,沐浴在这透亮清澈的蓝天里,那朵朵白云如同一朵棉絮,心意畅想....思绪外扬, 鱼和熊掌不可兼得 ...

  4. 服务管理之httpd

    目录 1. httpd简介 2. httpd版本 2.2 httpd-2.4新增的模块 3. httpd基础 3.1 httpd自带的工具程序 3.2 rpm包安装的httpd程序环境 3.3 web ...

  5. HTML5-之workers(多线程执行)

    注:test.js 不涉及DOM元素

  6. AX_SysTableBrowser

    sysTableBrowser sysTableBrowser = new sysTableBrowser();  ;  sysTableBrowser.setAllowEdit(true);  sy ...

  7. ----关于统计字符出现次数的JS循环以及indesxOf函数----

    以下将会通过JS循环判断字符“banana”出现次数 以及调用indexOf中的函数来实现统计   <!DOCTYPE html> <html> <body> &l ...

  8. 微信小程序开发之搞懂flex布局2——flex container

    容器的概念,是用来包含其它容器(container)和项目(item). flex container——flex容器 A flexbox layout is defined using the fl ...

  9. 使用Jmeter进行http接口做功能、性能测试

    在测试移动APP时,会有很多接口需要做测试,我在这里介绍一下对HTTP接口做功能.性能的测试.首先我们会从开发人员拿到接口数据.     一.测试需求描述 1. 本次测试的接口为http服务端接口 2 ...

  10. Vue 去掉#号,让网址像正常的一样

    vue利用hash模式让页面不刷新,但是有时候看起来觉得怪怪的,也可以去掉#,并像#模式一样不刷新页面. 1.在路由里面添加     mode: 'history' 这样就去掉了#号,但是点击页面会发 ...