-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathSeparateChainingHashST.h
58 lines (42 loc) · 1.43 KB
/
SeparateChainingHashST.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
#ifndef ALGS4_SEPARATECHAININGHASHST_H
#define ALGS4_SEPARATECHAININGHASHST_H
#include <functional>
#include <vector>
#include "SequentialSearchST.h"
#include "ST.h"
template<typename Key, typename Value>
class SeparateChainingHashST : public ST<Key, Value> {
private:
int M; // hash table size
std::vector<SequentialSearchST<Key, Value> > st;
int hash(const Key &key) const;
public:
explicit SeparateChainingHashST(int M) : M(M), st(M) {}
std::optional<Value> get(const Key &key) const override { return st[hash(key)].get(key); }
void put(const Key &key, const Value &val) override { st[hash(key)].put(key, val); }
void remove(const Key &key) override { st[hash(key)].remove(key); }
int size() const override;
std::list<Key> keys() const override;
};
template<typename Key, typename Value>
int SeparateChainingHashST<Key, Value>::hash(const Key &key) const {
std::hash<Key> hasher;
return hasher(key) % M;
}
template<typename Key, typename Value>
int SeparateChainingHashST<Key, Value>::size() const {
int N = 0;
for (int i = 0; i < M; ++i) N += st[i].size();
return N;
}
template<typename Key, typename Value>
std::list<Key> SeparateChainingHashST<Key, Value>::keys() const {
std::list<Key> queue;
for (int i = 0; i < M; ++i) {
for (const auto &key: st[i].keys()) {
queue.push_back(key);
}
}
return queue;
}
#endif //ALGS4_SEPARATECHAININGHASHST_H