diff options
| author | ckrinitsin <101062646+ckrinitsin@users.noreply.github.com> | 2025-03-20 12:15:53 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-03-20 12:15:53 +0100 |
| commit | ae8de5f25623ed6f39f8f6c9c0f837c8f286b8c0 (patch) | |
| tree | ffae5c5b9498ce82fe53244aebb7c7dafc46d4ab /src/server/hashtable.h | |
| parent | 481c97567aa1cb54edd169841d1266a7a59a0227 (diff) | |
| parent | a509d8e7c953aa80eed3b7288bd3af9bca68dd48 (diff) | |
| download | BT-Programming-Assignment-ae8de5f25623ed6f39f8f6c9c0f837c8f286b8c0.tar.gz BT-Programming-Assignment-ae8de5f25623ed6f39f8f6c9c0f837c8f286b8c0.zip | |
Merge pull request #1 from ckrinitsin/hashtable
Hashtable
Diffstat (limited to 'src/server/hashtable.h')
| -rw-r--r-- | src/server/hashtable.h | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/src/server/hashtable.h b/src/server/hashtable.h new file mode 100644 index 0000000..0989a79 --- /dev/null +++ b/src/server/hashtable.h @@ -0,0 +1,92 @@ +#pragma once + +#include <algorithm> +#include <iostream> +#include <list> +#include <optional> +#include <vector> + +template <typename K, typename V> +class HashTable { +public: + HashTable(size_t size) + : size { size } + , table(size) + { + } + + bool insert(K key, V value) + { + std::list<std::pair<K, V>>& list = get_bucket(key); + + if (bucket_contains_key(list, key)) { + return false; + } + + list.push_back(std::pair(key, value)); + + return true; + } + + std::optional<V> get(K key) + { + std::list<std::pair<K, V>>& list = get_bucket(key); + + auto iter = bucket_find_key(list, key); + if (iter != list.end()) { + return std::optional<V>((*iter).second); + } + + return std::optional<V>(); + } + + bool remove(K key) + { + std::list<std::pair<K, V>>& list = get_bucket(key); + + auto iter = bucket_find_key(list, key); + if (iter != list.end()) { + list.erase(iter); + return true; + } + + return false; + } + + void print() + { + size_t index { 0 }; + for (auto bucket : table) { + std::cout << "Bucket " << index++ << ": ["; + for (auto pair : bucket) { + std::cout << "(" << pair.first << ", " << pair.second << ")"; + } + std::cout << "]" << "\n"; + } + } + +private: + size_t size; + + std::vector<std::list<std::pair<K, V>>> table; + + std::hash<K> hash_function; + + auto bucket_find_key(std::list<std::pair<K, V>>& list, K key) + { + return std::find_if(list.begin(), list.end(), [&key](const std::pair<K, V>& pair) { + return pair.first == key; + }); + } + + bool bucket_contains_key(std::list<std::pair<K, V>>& list, K key) + { + return list.begin() != list.end() && bucket_find_key(list, key) != list.end(); + } + + std::list<std::pair<K, V>>& get_bucket(K key) + { + size_t index = hash_function(key) % size; + return table.at(index); + } +}; |