-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.cpp
40 lines (35 loc) · 1009 Bytes
/
HashTable.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
#include <bits/stdc++.h>
using namespace std;
template<class K, class V, int MOD = 666013>
class HashTable {
function<int(K)> hash;
vector<vector<pair<K, V>>> table;
public:
HashTable(function<int(K)> hash = [](K key) {
return abs(key) % MOD;
}) : hash(hash), table(MOD) { }
V& operator[](K key) {
const int h = hash(key);
for (auto& [itKey, itVal] : table[h])
if (itKey == key)
return itVal;
table[h].emplace_back(key, V());
return table[h].back().second;
}
void erase(K key) {
const int h = hash(key);
for (auto& [itKey, itVal] : table[h])
if (itKey == key) {
tie(itKey, itVal) = table[h].back();
table[h].pop_back();
return;
}
}
int count(K key) {
const int h = hash(key);
for (auto [itKey, itVal] : table[h])
if (itKey == key)
return 1;
return 0;
}
};