Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
- //
- #include "pch.h"
- #include <iostream>
- #include <string>
- template <typename K, typename V>
- struct Node
- {
- K key;
- V value;
- Node<K, V> *next;
- Node(K k, V v)
- {
- key = k;
- value = v;
- next = nullptr;
- }
- };
- template <typename K, typename V>
- struct HashTable
- {
- int partitions_size;
- Node<K, V> **partitions;
- HashTable(int ps)
- {
- partitions_size = ps;
- partitions = new Node<K, V> *[partitions_size];
- for (int i = 0; i < partitions_size; i++)
- {
- partitions[i] = nullptr;
- }
- }
- ~HashTable()
- {
- delete[] partitions;
- }
- void insert(K key, V value)
- {
- int hash = hash_function(key);
- if (partitions[hash] == nullptr)
- {
- partitions[hash] = new Node<K, V>(key, value);
- }
- else
- {
- Node<K, V> *p = partitions[hash];
- while (p->next != nullptr)
- {
- p = p->next;
- }
- p->next = new Node<K, V>(key, value);
- }
- }
- void display()
- {
- int ct = 0;
- for (int i = 0; i < partitions_size; i++)
- {
- int c = 0;
- std::cout << "partitia " << i << ": ";
- if (partitions[i] == nullptr)
- {
- std::cout << "(empty) ";
- }
- else
- {
- Node<K, V> *p = partitions[i];
- while (p != nullptr)
- {
- c++;
- std::cout << "(k: " << p->key << ", v: " << p->value << ") ";
- p = p->next;
- }
- c = c - 1;
- }
- std::cout << "- " << c << " coliziuni" << std::endl;
- ct += c;
- }
- std::cout << ct << " coliziuni in total" << std::endl;
- }
- int hash_function(int key)
- {
- return key % partitions_size;
- }
- int hash_function(std::string key)
- {
- int hash = 0;
- for (int i = 0; i < key.length(); i++)
- {
- hash = hash ^ key[i];
- }
- return hash % partitions_size;
- }
- };
- int main()
- {
- HashTable<int, std::string> test1(5);
- test1.insert(1, "value 1");
- test1.insert(2, "value 2");
- test1.insert(3, "value 3");
- test1.display();
- HashTable<std::string, std::string> test2(5);
- test2.insert("key 1", "value 1");
- test2.insert("key 2", "value 2");
- test2.insert("key 3", "value 3");
- test2.display();
- }
- // Run program: Ctrl + F5 or Debug > Start Without Debugging menu
- // Debug program: F5 or Debug > Start Debugging menu
- // Tips for Getting Started:
- // 1. Use the Solution Explorer window to add/manage files
- // 2. Use the Team Explorer window to connect to source control
- // 3. Use the Output window to see build output and other messages
- // 4. Use the Error List window to view errors
- // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
- // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement