Advertisement
Guest User

Untitled

a guest
Dec 7th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. #ifndef LR5FORKIRILL_HASHTABLE_H
  2. #define LR5FORKIRILL_HASHTABLE_H
  3.  
  4. #include <vector>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. namespace hashTable {
  10. template<class Elem1, class Elem2>
  11. class Table {
  12. private:
  13. struct node {
  14. Elem1 key;
  15. Elem2 value;
  16.  
  17. node() {
  18. this->key = "";
  19. this->value = "";
  20. }
  21.  
  22. node(Elem1 key, Elem2 value) {
  23. this->key = key;
  24. this->value = value;
  25. }
  26.  
  27. bool isEmpty() {
  28. return key == "" && value == "";
  29. }
  30. };
  31.  
  32. int tableSize;
  33. int initialSize;
  34. vector<node> hashTable;
  35.  
  36. int hashFunc(const string &key) { //хэш-функция
  37. int hashCode = 0;
  38. for (char i : key) { //считаем сумму аски кодов символов ключа
  39. hashCode += (int) i;
  40. }
  41. //return 3;
  42. return hashCode % initialSize; //берем остаток от размера массива
  43. }
  44.  
  45. public:
  46. Table(int size = 100) {
  47. tableSize = size;
  48. initialSize = size;
  49. hashTable = vector<node>(size);
  50. }
  51.  
  52. void printTable() {
  53. for (int i = 0; i < tableSize; i++) {
  54. if(!(hashTable.at(i)).isEmpty())
  55. cout << i << " "<< (hashTable.at(i)).key << " " << (hashTable.at(i)).value << endl;
  56. }
  57. }
  58.  
  59. void insert(Elem1 key, Elem2 value){
  60. int index = hashFunc((string)key);
  61. for(int i = index; i < tableSize; i++){
  62. if((hashTable.at(i)).isEmpty() || (hashTable.at(i)).key == key) {
  63. hashTable.at(i) = node(key, value);
  64. return;
  65. }
  66. }
  67. hashTable.push_back(node(key, value));
  68. tableSize++;
  69. }
  70.  
  71. string search(Elem1 key){
  72. int index = hashFunc((string)key);
  73. for(int i = index - 1; i < tableSize; i++){
  74. if((hashTable.at(i)).key == key) {
  75. return (hashTable.at(i)).value;
  76. }
  77. }
  78. return "";
  79. }
  80.  
  81. bool del(Elem1 key){
  82. int index = hashFunc((string)key);
  83. for(int i = index; i < tableSize; i++){
  84. if((hashTable.at(i)).key == key) {
  85. hashTable.at(i) = node();
  86. return true;
  87. }
  88. }
  89. return false;
  90. }
  91.  
  92. };
  93. }
  94.  
  95. #endif //LR5FORKIRILL_HASHTABLE_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement