Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdexcept>
- #include <optional>
- #include <map>
- #include <iterator>
- using namespace std;
- template <typename Key1, typename Key2, typename Value>
- class BiMap {
- public:
- map<Key1, Value> mp1;
- map<Key2, Value> mp2;
- // Вставить значение, указав один или оба ключа.
- // Генерирует исключение std::invalid_argument("some text") в случае,
- // если оба ключа пусты, либо один из ключей уже имеется в хранилище.
- void Insert(const std::optional<Key1>& key1, const std::optional<Key2>& key2, const Value& value) {
- if((!key1.has_value() && !key2.has_value()) ||
- mp1.find(key1) != mp1.end() || mp2.template find(key2) != mp2.end()) {
- throw invalid_argument("bruh moment");
- } else {
- if(key1.has_value() && key2.has_value()) {
- mp1.template insert(make_pair(key1, value));
- mp2[key2] = value;
- } else if(!key1.has_value() && key2.has_value()) {
- mp2[key2] = value;
- } else {
- mp1[key1] = value;
- }
- }
- }
- // Получить значение по ключу первого типа.
- // Генерирует исключение std::out_of_range("some text")
- // в случае отсутствия ключа (как и функция at в std::map).
- Value& GetByPrimaryKey(const Key1& key) {
- try {
- return mp1.at(key);
- } catch (out_of_range ex) {}
- }
- const Value& GetByPrimaryKey(const Key1& key) const {
- try {
- return mp1.at(key);
- } catch (out_of_range ex) {}
- }
- // Аналогичная функция для ключа второго типа.
- Value& GetBySecondaryKey(const Key2& key) {
- try {
- return mp2.at(key);
- } catch (out_of_range ex) {}
- }
- const Value& GetBySecondaryKey(const Key2& key) const {
- try {
- return mp2.at(key);
- } catch (out_of_range ex) {}
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement