-
Notifications
You must be signed in to change notification settings - Fork 5
/
hash_map.h
76 lines (63 loc) · 1.56 KB
/
hash_map.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
//
// Created by codercat on 19-6-10.
//
#ifndef CPP_ALGORITHMS_HASH_MAP_H
#define CPP_ALGORITHMS_HASH_MAP_H
#include <cassert>
#include "avl_tree_map.h"
#include <iostream>
#include <optional>
using namespace std;
template<typename K, typename V>
class HashMap {
private:
unsigned M;
unsigned size;
AVLTreeMap<K, V> *hashtable;
int hash(string k) {
std::hash<string> hasher;
return hasher(k) % M;
}
public:
HashMap(int M = 73) {
this->M = M;
this->size = 0;
this->hashtable = new AVLTreeMap<K, V>[M];
}
void insert(K k, V v) {
unsigned index = this->hash(k);
assert(index < this->M);
if (!this->contrainsKey(k)) {
this->size ++;
}
this->hashtable[index].insert(k, v);
}
optional<V> find(K k) {
unsigned index = this->hash(k);
if (index > this->M) {
return optional<V>();
}
return this->hashtable[index].find(k);
}
bool contrainsKey(K k) {
unsigned index = this->hash(k);
if ((index < this->M) && this->hashtable[index].contrainsKey(k)) {
return true;
}
return false;
}
void remove(K k) {
unsigned index = this->hash(k);
if ((index < this->M) && this->hashtable[index].contrainsKey(k)) {
this->hashtable[index].remove(k);
this->size --;
}
}
bool isEmpty() {
return this->getSize() == 0;
}
unsigned getSize() {
return this->size;
}
};
#endif //CPP_ALGORITHMS_HASH_MAP_H