Skip to content

Commit e9035a6

Browse files
committed
perf: enhanced hashmap implementation
1 parent c7301ec commit e9035a6

1 file changed

Lines changed: 38 additions & 31 deletions

File tree

src/alfred/data_structure/hashmap.hpp

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,43 +4,50 @@
44
#include <utility>
55
#include <vector>
66

7-
template <class K, class V, size_t SIZE = 3301>
8-
struct HashMap {
9-
std::vector<std::pair<K, V>> vec[SIZE];
10-
HashMap(void) {}
11-
inline int hash_key(K key) { return key % SIZE; }
12-
inline auto find_it(int h, K key) {
13-
return std::find_if(vec[h].begin(), vec[h].end(), [&](auto kv) {
14-
return kv.first == key;
15-
});
7+
template <class K, class V>
8+
struct HashedMap {
9+
using u32 = unsigned int;
10+
struct Node {
11+
K key;
12+
V val;
13+
u32 ne;
14+
};
15+
u32 lim, mask, tot;
16+
std::vector<u32> fi;
17+
std::vector<Node> e;
18+
inline void init(u32 sz) {
19+
sz += 1;
20+
u32 lim = 1;
21+
while (lim < sz) lim <<= 1;
22+
fi.assign(lim, 0), tot = 0;
23+
mask = lim - 1, e.resize(sz);
1624
}
17-
inline void inc(K key) {
18-
int h = hash_key(key);
19-
auto it = find_it(h, key);
20-
if (it == vec[h].end()) {
21-
vec[h].emplace_back(key, 1);
22-
return;
25+
inline void inc(K x) {
26+
u32 u = x & mask;
27+
for (u32 i = fi[u]; i; i = e[i].ne) {
28+
if (e[i].key == x) {
29+
e[i].val++;
30+
return;
31+
}
2332
}
24-
it->second++;
33+
e[++tot] = {x, 1, fi[u]}, fi[u] = tot;
2534
}
26-
inline void dec(K key) {
27-
int h = hash_key(key);
28-
auto it = find_it(h, key);
29-
if (it == vec[h].end()) {
30-
return;
31-
}
32-
it->second--;
33-
if (it->second == 0) {
34-
vec[h].erase(it);
35+
inline void dec(K x) {
36+
u32 u = x & mask;
37+
for (u32 i = fi[u]; i; i = e[i].ne) {
38+
if (e[i].key == x) {
39+
e[i].val--;
40+
return;
41+
}
3542
}
43+
e[++tot] = {x, 1, fi[u]}, fi[u] = tot;
3644
}
37-
inline V get(K key) {
38-
int h = hash_key(key);
39-
auto it = find_it(h, key);
40-
if (it == vec[h].end()) {
41-
return 0;
45+
inline V query(K x) {
46+
u32 u = x & mask;
47+
for (u32 i = fi[u]; i; i = e[i].ne) {
48+
if (e[i].key == x) return e[i].val;
4249
}
43-
return it->second;
50+
return 0;
4451
}
4552
};
4653

0 commit comments

Comments
 (0)