CellModules
ordered_hash_map.hpp
Go to the documentation of this file.
1#ifndef ORDERED_HASH_MAP_HPP
2#define ORDERED_HASH_MAP_HPP
3#include <unordered_map>
4#include <vector>
5namespace MecaCell {
6template <typename K, typename V> struct ordered_hash_map {
7 // deterministic ordered hash_map
8 std::unordered_map<K, size_t> um;
10
11 V &operator[](const K &k) {
12 if (!um.count(k)) {
13 um[k] = vec.size();
14 vec.push_back({k, V{}});
15 }
16 return vec[um[k]].second;
17 }
18
19 bool count(const K &k) { return um.count(k); }
20 size_t size() const { return vec.size(); }
21 V &at(const K &k) { return vec[um.at(k)].second; }
22 void erase(const K &k) {
23 if (um.count(k)) {
24 const size_t id = um[k];
25 if (id < vec.size() - 1) {
26 vec[id] = std::move(vec.back());
27 um[vec[id].first] = id;
28 }
29 vec.pop_back();
30 um.erase(k);
31 }
32 }
33 using const_iterator = typename decltype(vec)::const_iterator;
34 using iterator = typename decltype(vec)::iterator;
35 const_iterator begin() const { return vec.begin(); }
36 const_iterator end() const { return vec.end(); }
37 iterator begin() { return vec.begin(); }
38 iterator end() { return vec.end(); }
39};
40} // namespace MecaCell
41#endif
CGAL::Exact_predicates_inexact_constructions_kernel K
A simple vector class template.
Definition: std.hpp:290
void pop_back()
Removes the last element of the vector.
Definition: std.hpp:311
void push_back(const T &value)
Adds an element to the end of the vector.
Definition: std.hpp:304
iterator begin()
Returns an iterator to the first element.
Definition: std.hpp:409
iterator end()
Returns an iterator to the last element.
Definition: std.hpp:418
size_t size() const
Returns the number of elements in the vector.
Definition: std.hpp:320
T & back()
Returns a reference to the last element.
Definition: std.hpp:338
this file contains various miscellanious utility functions & helpers *
const_iterator begin() const
typename decltype(vec)::iterator iterator
typename decltype(vec)::const_iterator const_iterator
std::vector< std::pair< K, V > > vec
const_iterator end() const
std::unordered_map< K, size_t > um