| 12 | |
| 13 | template<typename K, typename V, typename Hash = std::hash<K>, typename Pred = std::equal_to<K>> |
| 14 | class HashMap { |
| 15 | public: |
| 16 | class Entry { |
| 17 | public: |
| 18 | Entry(const K &k, const V &v) : key(k), value(v) {} |
| 19 | |
| 20 | Entry(const Entry &) = delete; |
| 21 | |
| 22 | Entry &operator=(const Entry &) = delete; |
| 23 | |
| 24 | [[nodiscard]] K getKey() const { |
| 25 | return key; |
| 26 | } |
| 27 | |
| 28 | [[nodiscard]] V *getValue() const { |
| 29 | return &value; |
| 30 | } |
| 31 | |
| 32 | template<typename... Args> |
| 33 | void setValue(Args &&...args) const { |
| 34 | value = V(std::forward<Args>(args)...); |
| 35 | } |
| 36 | |
| 37 | void setValue(V &v) const { |
| 38 | value = v; |
| 39 | } |
| 40 | |
| 41 | private: |
| 42 | const K key; |
| 43 | mutable V value; |
| 44 | }; |
| 45 | |
| 46 | private: |
| 47 | std::unordered_map<K, std::shared_ptr<Entry>, Hash, Pred> backend; |
| 48 | public: |
| 49 | HashMap() = default; |
| 50 | |
| 51 | template<typename AnyMap> |
| 52 | explicit HashMap(const AnyMap &map) { |
| 53 | const auto entries = map.entrySet(); |
| 54 | for (const auto &entry: entries) { |
| 55 | backend.insert_or_assign(entry->getKey(), std::make_shared<Entry> |
| 56 | (entry->getKey(), *entry->getValue())); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | [[nodiscard]] std::set<std::shared_ptr<Entry>> entrySet() const { |
| 61 | std::set<std::shared_ptr<Entry>> copy = std::set<std::shared_ptr<Entry>>(); |
| 62 | for (const auto &entry: backend) { |
| 63 | copy.emplace(entry.second); |
| 64 | } |
| 65 | return copy; |
| 66 | } |
| 67 | |
| 68 | [[nodiscard]] size_t size() const { |
| 69 | return backend.size(); |
| 70 | } |
| 71 |
no outgoing calls
no test coverage detected