Files
2026-02-01 22:23:06 +08:00

63 lines
1.1 KiB
C++

#pragma once
#include <unordered_map>
template<typename K, typename V>
class BijectiveMap {
private:
std::unordered_map<K, V> forward_map;
std::unordered_map<V, K> reverse_map;
public:
bool add(const K& key, const V& value)
{
if (forward_map.count(key) || reverse_map.count(value))
{
return false;
}
forward_map.emplace(key, value);
reverse_map.emplace(value, key);
return true;
}
bool remove(const K& key)
{
auto it = forward_map.find(key);
if (it!= forward_map.end())
{
V value = it->second;
forward_map.erase(it);
reverse_map.erase(value);
}
return false;
}
V getValue(const K& key)const
{
static V default_value{};
auto it = forward_map.find(key);
assert(it != forward_map.end() && "Value is invalid");
return it->second;
}
K getKey(const V& value) const
{
auto it = reverse_map.find(value);
assert(it != reverse_map.end() && " Key is invalid");
return it->second;
}
bool contiansKey (const K& key) const
{
return forward_map.count(key) > 0;
}
bool contiansValue(const V& vlaue)const
{
return reverse_map.count(vlaue)>0;
}
};