-
Notifications
You must be signed in to change notification settings - Fork 1
/
unordered_map.hpp
127 lines (105 loc) · 2.97 KB
/
unordered_map.hpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
template <typename Key, typename Value,size_t TableSize>
class MyUnorderedMap {
public:
struct Nodes {
Key key;
Value value;
Nodes* next;
Nodes(const Key& k,const Value &v)
: key(k), value(v), next(nullptr) {}
};
// 构造函数
MyUnorderedMap() {
table = new Nodes*[TableSize]();
}
// 析构函数
~MyUnorderedMap() {
clear();
delete[] table;
}
// 插入键值对
void insert(const Key& key, const Value& value) {
int index = hashFunction(key);
Nodes* newNode = new Nodes(key, value);
newNode->next = table[index];
table[index] = newNode;
}
// 删除键值对
void erase(const Key& key) {
int index = hashFunction(key);
Nodes* currNode = table[index];
Nodes* prevNode = nullptr;
while (currNode != nullptr) {
if (currNode->key == key) {
if (prevNode != nullptr)
prevNode->next = currNode->next;
else
table[index] = currNode->next;
delete currNode;
break;
}
prevNode = currNode;
currNode = currNode->next;
}
}
// 获取值
Value& operator[](const Key& key) {
int index = hashFunction(key);
Nodes* currNode = table[index];
while (currNode != nullptr) {
if (currNode->key == key)
return currNode->value;
currNode = currNode->next;
}
Nodes* newNode = new Nodes(key,Value());
newNode->next = table[index];
table[index] = newNode;
return newNode->value;
}
// 判断键是否存在
bool contains(const Key& key) const {
int index = hashFunction(key);
Nodes* currNode = table[index];
while (currNode != nullptr) {
if (currNode->key == key)
return true;
currNode = currNode->next;
}
return false;
}
// 获取键值对数量
size_t size() const {
size_t count = 0;
for (int i = 0; i < TableSize; i++) {
Nodes* currNode = table[i];
while (currNode != nullptr) {
count++;
currNode = currNode->next;
}
}
return count;
}
// 清空哈希表
void clear() {
for (int i = 0; i < TableSize; i++) {
Nodes* currNode = table[i];
while (currNode != nullptr) {
Nodes* nextNode = currNode->next;
delete currNode;
currNode = nextNode;
}
table[i] = nullptr;
}
}
// 哈希表节点定义
Nodes** table; // 哈希表数组
// 哈希函数
int hashFunction(const Key& key) const {
return std::hash<Key>()(key) % TableSize;
}
};