Skip to content

Instantly share code, notes, and snippets.

@SF-Zhou
Created July 25, 2018 07:37
Show Gist options
  • Save SF-Zhou/87ed9694eee15d971948f74e7f1c3fd0 to your computer and use it in GitHub Desktop.
Save SF-Zhou/87ed9694eee15d971948f74e7f1c3fd0 to your computer and use it in GitHub Desktop.
Hash Table, Clear Easily (C++ 11)
// Copyright [2018] <Copyright SF-Zhou>
// Author: SF-Zhou
// Email: [email protected]
#ifndef HASHTABLE_HPP_
#define HASHTABLE_HPP_
#include <cstring>
namespace Utils {
template <class Dtype, int Size>
class HashTable {
Dtype n[Size];
uint64_t s[Size];
int h[Size];
int v[Size];
int siz, id;
public:
HashTable() {
clear();
}
void clear() {
++id;
siz = 0;
}
void deep_clear() {
memset(v, 0, sizeof(v));
id = 1;
siz = 0;
}
int size() const {
return siz;
}
void set(uint64_t status, Dtype value) {
int hs = status % Size;
while (v[hs] == id && s[h[hs]] != status)
if (++hs == Size) hs = 0;
if (v[hs] != id) {
s[siz] = status;
n[siz] = value;
v[hs] = id;
h[hs] = siz;
++siz;
} else {
n[h[hs]] = value;
}
}
// NOLINTNEXTLINE(runtime/references)
bool get(uint64_t status, Dtype &value) {
int hs = status % Size;
while (v[hs] == id && s[h[hs]] != status)
if (++hs == Size) hs = 0;
if (v[hs] == id) {
value = n[h[hs]];
return true;
} else {
return false;
}
}
};
} // namespace Utils
#endif // HASHTABLE_HPP_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment