· 4 years ago · May 05, 2021, 08:00 PM
1#include <functional>
2#include <iostream>
3#include <list>
4
5template <typename Key, typename T, typename Hash = std::hash<Key>,
6 typename KeyEqual = std::equal_to<Key>>
7class HashTable {
8public:
9 /*
10 * See https://en.cppreference.com/w/cpp/container/unordered_map/unordered_map (1)
11 *
12 * Constructs new container. The number of buckets to create is implementation-defined.
13 */
14 HashTable();
15
16 /*
17 * See https://en.cppreference.com/w/cpp/container/unordered_map/unordered_map (1)
18 *
19 * Constructs new container, uses bucket_count parameter as a minimal number of buckets to
20 * create.
21 */
22 explicit HashTable(size_t bucket_count) {
23 count_bucket_ = bucket_count;
24 table_ = new std::list<Key, T>[bucket_count];
25 count_ = 0;
26 };
27
28 HashTable(const HashTable& other) {
29 *this = other;
30 };
31
32 ~HashTable() {
33 Clear();
34 };
35
36 /*
37 * See https://en.cppreference.com/w/cpp/container/unordered_map/empty
38 *
39 * Returns true if the tree is empty, false otherwise
40 */
41 bool Empty() const {
42 return (count_ == 0);
43 };
44
45 /*
46 * See https://en.cppreference.com/w/cpp/container/unordered_map/size
47 *
48 * Returns the number of elements in the container
49 */
50 size_t Size() const {
51 return count_;
52 };
53
54 /*
55 * See https://en.cppreference.com/w/cpp/container/unordered_map/clear
56 *
57 * Erases all elements from the container.
58 */
59 void Clear();
60
61 /*
62 * See https://en.cppreference.com/w/cpp/container/unordered_map/insert
63 *
64 * Returns a bool value set to true if the insertion took place.
65 */
66 bool Insert(const Key& key, const T& value) {
67 if (!Contains(key)) {
68 Hash index = hash_(key);
69 table_[index].push_back(key, value);
70 count_ ++;
71 return true;
72 } else {
73 return false;
74 }
75
76 };
77
78 /*
79 * See https://en.cppreference.com/w/cpp/container/unordered_map/erase
80 *
81 * Removes the element from the container with set key.
82 * Returns true if the erase took place.
83 */
84 bool Erase(const Key& key) {
85 if (Contains(key)) {
86
87
88 }
89 };
90
91 /*
92 * See https://en.cppreference.com/w/cpp/container/unordered_map/contains
93 *
94 * Returns true if an element with key equivalent to value exists in the container.
95 */
96 bool Contains(const Key& key) const;
97
98 /*
99 * See https://en.cppreference.com/w/cpp/container/unordered_map/operator_at
100 *
101 * Returns a reference to the value that is mapped to a key equivalent to key, performing an
102 * insertion if such key does not already exist.
103 */
104 T& operator[](const Key& key);
105
106private:
107 size_t count_bucket_;
108 KeyEqual equal_;
109 std::list<Key, T>* table_;
110 Hash hash_;
111 size_t count_;
112};