Advertisement
evcamels

course

Jan 19th, 2021
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <iomanip>      // std::setprecision
  5. #include <cmath>
  6. using namespace std;
  7.  
  8. class Hash
  9. {
  10.     int BUCKET;    //bucket
  11.  
  12.     //
  13. Указатель на массив, содержащий bucket
  14.     list<int> *table;
  15. public:
  16.     Hash(int V);  // конструктор
  17.  
  18.     // вставляет ключ в хеш-таблицу
  19.     void insertItem(int x);
  20.  
  21.     // удаляет ключ из хеш-таблицы
  22.     void deleteItem(int key);
  23.  
  24.     // хэш-функция для сопоставления значений с ключом
  25.     int hashFunction(int x) {
  26.         return (x % BUCKET);
  27.     }
  28.  
  29.     void displayHash();
  30. };
  31.  
  32. Hash::Hash(int b)
  33. {
  34.     this->BUCKET = b;
  35.     table = new list<int>[BUCKET];
  36. }
  37.  
  38. void Hash::insertItem(int key)
  39. {
  40.     int index = hashFunction(key);
  41.     table[index].push_back(key);  
  42. }
  43.  
  44. void Hash::deleteItem(int key)
  45. {
  46.   // получить хеш-индекс ключа
  47.   int index = hashFunction(key);
  48.  
  49.   // найти ключ в (inex)th list
  50.   list <int> :: iterator i;
  51.   for (i = table[index].begin();
  52.            i != table[index].end(); i++) {
  53.     if (*i == key)
  54.       break;
  55.   }
  56.  
  57.   // если ключ не найден в хеш таблице удалить его
  58.   if (i != table[index].end())
  59.     table[index].erase(i);
  60. }
  61.  
  62. // функция для показа хеш таблицы
  63. void Hash::displayHash() {
  64.   for (int i = 0; i < BUCKET; i++) {
  65.     cout << i;
  66.     for (auto x : table[i])
  67.       cout << " --> " << x;
  68.     cout << endl;
  69.   }
  70. }
  71.  
  72. // главная функция
  73. int main()
  74. {
  75.   // массив, содержащий ключи для отображения
  76.   int a[] = {15, 11, 27, 8, 12};
  77.   int n = sizeof(a)/sizeof(a[0]);
  78.  
  79.   // вставить ключи в хеш-таблицу
  80.   Hash h(7);   // 7 счетчик buckets
  81.                // хеш таблица
  82.   for (int i = 0; i < n; i++)  
  83.     h.insertItem(a[i]);  
  84.  
  85.   // удалить 12 из хеш-таблицы
  86.   h.deleteItem(12);
  87.  
  88.   // отобразить хеш-таблицу
  89.   h.displayHash();
  90.  
  91.   return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement