-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_table.cpp
101 lines (84 loc) · 1.7 KB
/
hash_table.cpp
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
#include <vector>
#include <list>
#include <algorithm>
#include <string>
template<typename HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101):mSize{size}{}
constexpr bool Contains(const HashedObj& x) const;
void Clear();
bool Insert(const HashedObj& x);
bool Insert(HashedObj&& x);
bool Remove(const HashedObj& x);
private:
std::vector<std::list<HashedObj>> mLists; // The array of Lists
int mSize;
void rehash();
size_t hash(const HashedObj& x) const;
};
template<typename Key>
class Hash
{
public:
size_t operator() (const Key& k) const;
};
template<typename HashedObj>
size_t HashTable<HashedObj>::hash(const HashedObj& x) const
{
static Hash<HashedObj> hf;
return hf(x) % mLists.size();
}
template<typename HashedObj>
void HashTable<HashedObj>::Clear()
{
for(auto& list : mLists)
{
list.clear();
}
}
template<typename HashedObj>
constexpr bool HashTable<HashedObj>::Contains(const HashedObj& x) const
{
auto& list = mLists[hash(x)];
return std::find(begin(list), end(list), x) != end(list);
}
template<typename HashedObj>
bool HashTable<HashedObj>::Remove(const HashedObj& x)
{
auto& list = mLists[hash(x)];
auto itr = std::find(begin(list), end(list), x);
if(itr == end(list))
{
return false;
}
list.erase(itr);
--mSize;
return true;
}
template<typename HashedObj>
bool HashTable<HashedObj>::Insert(const HashedObj& x)
{
auto& list = mLists[hash(x)];
if(std::find(begin(list), end(list), x) != end(list))
{
return false;
}
list.push_back(x);
// rehash;
if(++mSize > mLists.size())
{
rehash();
}
return true;
}
int main()
{
HashTable<std::string> h{};
//h.Insert("aa");
//h.Insert("bb");
//h.Insert("cc");
//h.Insert("dd");
//h.Insert("ee");
}