Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5. #include <math.h>
  6. #include <list>
  7. #include <algorithm>
  8.  
  9. using namespace std;
  10.  
  11. template<typename T1, typename T2>
  12. class Map {
  13. private:
  14. const int PRIME_SIZE = 200003;
  15. vector<list<pair<T1, T2>>>* hashTable;
  16.  
  17. int hash(T1 key) const {
  18. unsigned long hash = 5381;
  19. for (auto i : key)
  20. hash = ((hash << 5) + hash) + i;
  21. return hash % PRIME_SIZE;
  22. }
  23.  
  24. public:
  25. Map() {
  26. this->hashTable = new vector<list<pair<T1, T2>>>(PRIME_SIZE);
  27. }
  28. ~Map() {
  29. delete this->hashTable;
  30. }
  31. void insert(pair<T1, T2> pair) {
  32. auto collision_list = &hashTable->at(hash(pair.first));
  33. auto key = pair.first;
  34. auto find_iter = find_if(collision_list->begin(), collision_list->end(), [key](const std::pair<T1, T2>& p) {
  35. return key == p.first;
  36. });
  37. if (find_iter == collision_list->end())
  38. collision_list->push_back(pair);
  39. else
  40. find_iter->second = pair.second;
  41. }
  42. void erase(T1 key) {
  43. auto collision_list = &hashTable->at(hash(key));
  44. auto find_iter = find_if(collision_list->begin(), collision_list->end(), [key](const pair<T1, T2>& p) {
  45. return key == p.first;
  46. });
  47. if (find_iter != collision_list->end())
  48. collision_list->erase(find_iter);
  49. }
  50. auto find(T1 key) const {
  51. int index = hash(key);
  52. return find_if(hashTable->at(index).begin(), hashTable->at(index).end(), [key](const pair<T1, T2>& p) {
  53. return key == p.first;
  54. });
  55. }
  56.  
  57. T2 get(T1 key) {
  58.  
  59. auto collision_list = &hashTable->at(hash(key));
  60. auto find_iter = find_if(collision_list->begin(), collision_list->end(), [key](const std::pair<T1, T2>& p) {
  61. return key == p.first;
  62. });
  63.  
  64. if (find_iter != collision_list->end())
  65. return find_iter->second;
  66. else
  67. return T2();
  68. }
  69.  
  70. };
  71.  
  72.  
  73. int main() {
  74. ifstream ist("map.in");
  75. ofstream ost("map.out");
  76.  
  77. Map<string, string> newMap;
  78.  
  79. string com;
  80. string key;
  81. while (ist >> com >> key) {
  82. if (com == "put") {
  83. string value;
  84. ist >> value;
  85. newMap.insert(make_pair(key, value));
  86. }
  87. else if (com == "delete")
  88. newMap.erase(key);
  89. else if (com == "get") {
  90. string find = newMap.get(key);
  91. ost << (find == "" ? "none" : find) << endl;
  92. }
  93. }
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement