-
Notifications
You must be signed in to change notification settings - Fork 3
/
HashTable.h
155 lines (129 loc) · 2.36 KB
/
HashTable.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
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#pragma once
// 分离链接法 Separate Chaining
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <functional>
#include <algorithm>
using std::vector;
using std::list;
using std::hash;
using std::string;
using std::cout;
int nextPrime(int value)
{
int currentValue = value + 1;
while (true)
{
bool flag = true;
for (int i = 2; i * i <= currentValue; ++i)
{
if (currentValue % i == 0)
{
flag = false;
break;
}
}
if (flag)
{
break;
}
++currentValue;
}
return currentValue;
}
template<typename HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101):
theLists(size, list<HashedObj>())
{}
bool contains(const HashedObj& x) const
{
auto& lt = theLists[myHash(x)];
return std::find(lt.begin(), lt.end(), x) != lt.end();
}
void makeEmpty()
{
for (list<HashedObj>& lt : theLists)
{
lt.clear();
}
}
bool insert(const HashedObj& x)
{
list<HashedObj>& lt = theLists[myHash(x)];
auto itr = std::find(lt.begin(), lt.end(), x);
if (itr != lt.end()) return false; // 已经存在
lt.push_back(x);
// 重新hash
if (++currentSize > theLists.size())
{
rehash();
}
return true;
}
bool insert(HashedObj&& x)
{
list<HashedObj>& lt = theLists[myHash(x)];
auto itr = std::find(lt.begin(), lt.end(), x);
if (itr != lt.end()) return false; // 已经存在
lt.push_back(std::move(x));
// 重新hash
if (++currentSize > theLists.size())
{
rehash();
}
return true;
}
bool remove(const HashedObj& x)
{
list<HashedObj>& lt = theLists[myHash(x)];
auto itr = std::find(lt.begin(), lt.end(), x);
if (itr == lt.end()) return false; // 不存在
lt.erase(itr);
--currentSize;
return true;
}
private:
vector<list<HashedObj>> theLists;
int currentSize;
void rehash()
{
vector<list<HashedObj>> oldLists = theLists;
theLists.resize(nextPrime(2 * theLists.size()));
for (auto& lt : theLists)
{
lt.clear();
}
currentSize = 0;
for (auto& lt : oldLists)
{
for (auto& x : lt)
{
insert(std::move(x));
}
}
};
size_t myHash(const HashedObj& x) const
{
static hash<HashedObj> hf;
return hf(x) % theLists.size();
}
};
template <>
class hash<string>
{
public:
size_t operator()(const string& key)
{
size_t hashVal = 0;
for (char c : key)
{
hashVal = 37 * hashVal + c;
}
return hashVal;
}
};