Skip to content

Instantly share code, notes, and snippets.

@elder-george
Created October 17, 2021 20:57
Show Gist options
  • Save elder-george/c9689ed15fa31eb84e782435179b3cd1 to your computer and use it in GitHub Desktop.
Save elder-george/c9689ed15fa31eb84e782435179b3cd1 to your computer and use it in GitHub Desktop.
open-addressing (linear probing) hashmap in C++ (possibly buggy)
struct oa_map {
using Store = std::vector<std::tuple<size_t, std::string, uint32_t>>;
using iterator = Store::iterator;
Store _store{1024};
std::pair<iterator, bool> try_emplace(std::string&& s, uint32_t v) {
auto full_h = std::hash<std::string>{}(s);
return try_emplace(full_h, std::move(s), v);
}
std::pair<iterator, bool> try_emplace(size_t full_h, std::string&& s, uint32_t v) {
auto h = full_h % _store.size();
for(auto it = _store.begin() + h; ; ++it) {
if (std::get<std::string>(*it).empty()) {
*it = {full_h, s, v};
return {it, true};
}
else if (std::get<std::string>(*it) == s) {
return {it, false};
}
else if (it + 1 == _store.end()) {
// hackish resize
_store.resize(_store.size() * 2);
// re-place existing values
for (auto i = 0; i < _store.size() / 2; ++i) {
auto [hash, key, value] = std::move(_store[i]);
try_emplace(hash, std::move(key), value);
}
// this time it'll succeed, right? RIGHT?
return try_emplace(full_h, std::move(s), v);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment