当前位置:   article > 正文

c++ 哈希表的实现_c++ hlist.h

c++ hlist.h

最近想自己写个lru缓存练练手,于是乎就从最基本的hashmap开始着手,原本打算用容器机制来实现的,后来想想直接用模板能省不少力,不过每个溢出链表的空间多了不少。

  1. #include <cstdlib>
  2. #include <iostream>
  3. #include <string>
  4. #define HASHSIZE 4096
  5. using namespace std;
  6. template<class T>
  7. class HashMap
  8. {
  9. private:
  10. struct hlist_node
  11. {
  12. hlist_node *next, **prev;
  13. string key;
  14. T* value;
  15. hlist_node(hlist_node* next_in = 0, hlist_node** prev_in = 0, string key_in = "", T* value_in = 0):next(next_in), prev(prev_in), key(key_in), value(value_in){}
  16. ~hlist_node(){}
  17. };
  18. struct hlist_head
  19. {
  20. hlist_node *first;
  21. hlist_head():first(0){}
  22. ~hlist_head(){}
  23. };
  24. hlist_head* map;
  25. int size;
  26. long hash(const string &str);
  27. public:
  28. HashMap(int h_size = HASHSIZE):size(h_size){map = new hlist_head[h_size];}
  29. ~HashMap(){delete []map;}
  30. void insert(const string key, T* data);
  31. void remove(const string &key);
  32. T* search(const string &key);
  33. };
  34. template<class T>
  35. T* HashMap<T>::search(const string &key)
  36. {
  37. hlist_node* node = map[hash(key) % size].first;
  38. while( 0 != node)
  39. {
  40. if(node -> key == key)
  41. return node -> value;
  42. node = node -> next;
  43. }
  44. return 0;
  45. }
  46. template<class T>
  47. void HashMap<T>::insert(const string key, T* data)
  48. {
  49. //insert a key-value pair
  50. hlist_node* node = new hlist_node();
  51. hlist_node* first = map[hash(key) % size].first;
  52. if(first)
  53. first->prev = &node->next;
  54. map[hash(key) % size].first = node;
  55. node -> prev = &map[hash(key) % size].first;
  56. node -> key = key;
  57. node -> value = data;
  58. }
  59. template<class T>
  60. void HashMap<T>::remove(const string &key)
  61. hlist_node* node = map[hash(key) % size].first;
  62. while(0 != node)
  63. {
  64. if(node -> key == key)
  65. {
  66. struct hlist_node * next = node -> next;
  67. struct hlist_node ** prev = node -> prev;
  68. *prev = next;
  69. if(next)
  70. next -> prev = prev;
  71. delete node;
  72. return;
  73. }
  74. node = node -> next;
  75. }
  76. return;
  77. }
  78. template<class T>
  79. long HashMap<T>::hash(const string &str)
  80. {
  81. //BKD hash algorithm
  82. long seed = 131;
  83. long hash = 0;
  84. for(int i = 0; i < str.length(); i++)
  85. {
  86. hash = (hash * seed) + str[i];
  87. }
  88. return hash;
  89. }
  90. int main()
  91. {
  92. HashMap<int> testhash ;
  93. int t1 = 10;
  94. int t2 = 11;
  95. string s1 = "aaa";
  96. string s2 = "bbb";
  97. a.insert(s1, &t1);
  98. a.insert(s2, &t2);
  99. //a.remove(s1);
  100. int * tmp = a.search(s1);
  101. cout<<*tmp<<endl;
  102. return 0;
  103. }



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/955666
推荐阅读
相关标签
  

闽ICP备14008679号