2020-03-22 15:38:48 +00:00
|
|
|
#ifndef ARBUTILS_DICTIONARY_HPP
|
|
|
|
#define ARBUTILS_DICTIONARY_HPP
|
|
|
|
#include <unordered_map>
|
2020-03-22 15:43:31 +00:00
|
|
|
#include "../Assert.hpp"
|
2020-03-22 15:38:48 +00:00
|
|
|
|
|
|
|
namespace Arbutils::Collections {
|
|
|
|
template <class KeyT, class ValueT> class Dictionary {
|
|
|
|
private:
|
|
|
|
std::unordered_map<KeyT, ValueT> _map;
|
|
|
|
|
2020-03-22 16:09:25 +00:00
|
|
|
using iterator = typename std::unordered_map<KeyT, ValueT>::iterator;
|
2020-03-22 15:38:48 +00:00
|
|
|
public:
|
2020-03-22 15:55:07 +00:00
|
|
|
Dictionary() : _map() {}
|
2020-03-22 15:38:48 +00:00
|
|
|
explicit Dictionary(size_t capacity) : _map(capacity) {}
|
2020-03-22 15:53:42 +00:00
|
|
|
explicit Dictionary(const std::initializer_list<std::pair<const KeyT, ValueT>>& l) : _map(l){}
|
2020-03-22 15:38:48 +00:00
|
|
|
|
|
|
|
inline void Insert(KeyT key, ValueT value) {
|
|
|
|
auto v = _map.insert({key, value});
|
2020-03-22 15:43:31 +00:00
|
|
|
#ifndef NO_ASSERT
|
2020-03-22 15:38:48 +00:00
|
|
|
if (!v.second)
|
|
|
|
throw std::logic_error("Key already exists");
|
2020-03-22 15:43:31 +00:00
|
|
|
#endif
|
2020-03-22 15:38:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
inline void Set(KeyT key, ValueT value) { _map[key] = value; }
|
|
|
|
|
|
|
|
[[nodiscard]] inline ValueT& Get(KeyT key) {
|
2020-03-22 15:43:31 +00:00
|
|
|
#ifndef NO_ASSERT
|
2020-03-22 15:38:48 +00:00
|
|
|
auto find = _map.find(key);
|
|
|
|
if (find == _map.end()) {
|
|
|
|
throw std::logic_error("Key not found");
|
|
|
|
}
|
|
|
|
return find->second;
|
2020-03-22 15:43:31 +00:00
|
|
|
#else
|
|
|
|
return _map[key];
|
|
|
|
#endif
|
2020-03-22 15:38:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
[[nodiscard]] inline const ValueT& Get(KeyT key) const {
|
2020-03-22 15:43:31 +00:00
|
|
|
#ifndef NO_ASSERT
|
2020-03-22 15:38:48 +00:00
|
|
|
auto find = _map.find(key);
|
|
|
|
if (find == _map.end()) {
|
|
|
|
throw std::logic_error("Key not found");
|
|
|
|
}
|
|
|
|
return find->second;
|
2020-03-22 15:43:31 +00:00
|
|
|
#else
|
|
|
|
return _map[key];
|
|
|
|
#endif
|
2020-03-22 15:38:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
inline bool TryGet(KeyT key, ValueT& out) const {
|
|
|
|
auto find = _map.find(key);
|
|
|
|
if (find == _map.end()) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
out = find->second;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
[[nodiscard]] inline size_t Count() const { return _map.size(); }
|
|
|
|
|
|
|
|
inline bool Has(KeyT key) const noexcept { return _map.find(key) != _map.end(); }
|
|
|
|
|
|
|
|
inline ValueT& operator[](KeyT key) { return Get(key); }
|
|
|
|
inline const ValueT& operator[](KeyT key) const { return Get(key); }
|
|
|
|
|
|
|
|
iterator begin() { return _map.begin(); }
|
|
|
|
iterator begin() const { return _map.begin(); }
|
|
|
|
|
|
|
|
iterator end() { return _map.end(); }
|
|
|
|
iterator end() const { return _map.end(); }
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif // ARBUTILS_DICTIONARY_HPP
|