maomao90's Library
A C++20 library for competitive programming.
Loading...
Searching...
No Matches
hashmap.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <bitset>
4#include <vector>
5
7
8namespace maomao90 {
9using namespace std;
10template <typename K, typename T,
12 bool KEEP_HISTORY = false, int LG = 20>
13struct HashMap {
14 constexpr T &operator[](const K &k) {
15 int index = get_index(k);
16 if (!vis[index]) {
17 vis[index] = 1;
18 key[index] = k;
19 value[index] = T();
20 if constexpr (KEEP_HISTORY) {
21 history.push_back(index);
22 }
23 }
24 return value[index];
25 }
26 constexpr bool erase(const K &k) {
27 int index = get_index(k);
28 if (!vis[index]) {
29 return 0;
30 }
31 vis[index] = 0;
32 return 1;
33 }
34 constexpr bool contains(const K &k) const {
35 int index = get_index(k);
36 return vis[index];
37 }
38
39 template <typename F>
40 requires requires(F f, const K &k, T &v) { f(k, v); }
41 constexpr void for_each(F f) {
42 if constexpr (KEEP_HISTORY) {
43 for (int i : history) {
44 if (vis[i]) {
45 f(key[i], value[i]);
46 }
47 }
48 } else {
49 for (int i = 0; i < MOD; i++) {
50 if (vis[i]) {
51 f(key[i], value[i]);
52 }
53 }
54 }
55 }
56
57 constexpr void clear() {
58 if constexpr (KEEP_HISTORY) {
59 for (int i : history) {
60 vis[i] = 0;
61 }
62 history.clear();
63 } else {
64 vis.reset();
65 }
66 }
67
68private:
69 static constexpr int MOD = 1 << LG;
70 bitset<MOD> vis;
71 K key[MOD];
72 T value[MOD];
73 vector<int> history;
74
75 constexpr int get_index(const K &k) const {
76 unsigned long long hash = Hash()(k);
77 int index = hash >> (64 - LG);
78 while (vis[index] && key[index] != k) {
79 index = (index + 1) & (MOD - 1);
80 }
81 return index;
82 }
83};
84} // namespace maomao90
Definition hashmap.hpp:8
Definition hashmap.hpp:13
constexpr bool contains(const K &k) const
Definition hashmap.hpp:34
constexpr T & operator[](const K &k)
Definition hashmap.hpp:14
constexpr bool erase(const K &k)
Definition hashmap.hpp:26
constexpr void for_each(F f)
Definition hashmap.hpp:41
constexpr void clear()
Definition hashmap.hpp:57