-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhashmap.h
82 lines (68 loc) · 1.99 KB
/
hashmap.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// https://aozturk.medium.com/simple-hash-map-hash-table-implementation-in-c-931965904250
#ifndef HASHMAP_H
#define HASHMAP_H
#include "hashnode.h"
#include <array>
#include <vector>
#include <iostream>
#include <cstddef>
template<typename K>
struct KeyHash
{
unsigned long operator() (const K& key, size_t tableSize)
{
return reinterpret_cast<unsigned long>(key) % tableSize;
}
};
template<typename K, typename V, std::size_t tableSize = 1024, typename F = KeyHash<K>>
class HashMap
{
private:
std::array<std::vector<HashNode<K, V>>, tableSize> table { };
F hashFunc;
public:
HashMap() = default;
~HashMap() = default;
void put(const K& key, const V& value)
{
unsigned long hash = hashFunc(key, tableSize);
for (auto node : table[hash]) {
if (node.getKey() == key) {
// key already present in map. Simply overwrite value
node.setValue(value);
return;
}
}
// Reached here means key is not present in map so simple insert new key-value pair
HashNode<K, V> node(key, value);
table[hash].push_back(node);
}
void remove(const K& key)
{
unsigned long hash = hashFunc(key, tableSize);
if (table[hash].size() == 1) {
// if table has only one key-value pair then reset the vector
if (table[hash][0].getKey() == key) {
table[hash].clear();
}
} else {
for (auto it = table[hash].begin(); it != table[hash].end(); ++it) {
if ((*it).getKey() == key) {
it = table[hash].erase(it);
}
}
}
}
bool get(const K& key, V& value)
{
unsigned long hash = hashFunc(key, tableSize);
for (auto node : table[hash]) {
if (node.getKey() == key) {
value = node.getValue();
return true;
}
}
return false;
}
};
#endif