Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <iomanip> // std::setprecision
- #include <cmath>
- using namespace std;
- class Hash
- {
- int BUCKET; //bucket
- //
- Указатель на массив, содержащий bucket
- list<int> *table;
- public:
- Hash(int V); // конструктор
- // вставляет ключ в хеш-таблицу
- void insertItem(int x);
- // удаляет ключ из хеш-таблицы
- void deleteItem(int key);
- // хэш-функция для сопоставления значений с ключом
- int hashFunction(int x) {
- return (x % BUCKET);
- }
- void displayHash();
- };
- Hash::Hash(int b)
- {
- this->BUCKET = b;
- table = new list<int>[BUCKET];
- }
- void Hash::insertItem(int key)
- {
- int index = hashFunction(key);
- table[index].push_back(key);
- }
- void Hash::deleteItem(int key)
- {
- // получить хеш-индекс ключа
- int index = hashFunction(key);
- // найти ключ в (inex)th list
- list <int> :: iterator i;
- for (i = table[index].begin();
- i != table[index].end(); i++) {
- if (*i == key)
- break;
- }
- // если ключ не найден в хеш таблице удалить его
- if (i != table[index].end())
- table[index].erase(i);
- }
- // функция для показа хеш таблицы
- void Hash::displayHash() {
- for (int i = 0; i < BUCKET; i++) {
- cout << i;
- for (auto x : table[i])
- cout << " --> " << x;
- cout << endl;
- }
- }
- // главная функция
- int main()
- {
- // массив, содержащий ключи для отображения
- int a[] = {15, 11, 27, 8, 12};
- int n = sizeof(a)/sizeof(a[0]);
- // вставить ключи в хеш-таблицу
- Hash h(7); // 7 счетчик buckets
- // хеш таблица
- for (int i = 0; i < n; i++)
- h.insertItem(a[i]);
- // удалить 12 из хеш-таблицы
- h.deleteItem(12);
- // отобразить хеш-таблицу
- h.displayHash();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement