Advertisement
MKcrazy8

Untitled

Jun 3rd, 2022
858
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <optional>
  4. #include <map>
  5. #include <iterator>
  6.  
  7. using namespace std;
  8.  
  9. template <typename Key1, typename Key2, typename Value>
  10. class BiMap {
  11. public:
  12.     map<Key1, Value> mp1;
  13.     map<Key2, Value> mp2;
  14.  
  15.     // Вставить значение, указав один или оба ключа.
  16.     // Генерирует исключение std::invalid_argument("some text") в случае,
  17.     // если оба ключа пусты, либо один из ключей уже имеется в хранилище.
  18.     void Insert(const std::optional<Key1>& key1, const std::optional<Key2>& key2, const Value& value) {
  19.         if((!key1.has_value() && !key2.has_value()) ||
  20.         mp1.find(key1) != mp1.end() || mp2.template find(key2) != mp2.end()) {
  21.             throw invalid_argument("bruh moment");
  22.         } else {
  23.             if(key1.has_value() && key2.has_value()) {
  24.                 mp1.template insert(make_pair(key1, value));
  25.                 mp2[key2] = value;
  26.             } else if(!key1.has_value() && key2.has_value()) {
  27.                 mp2[key2] = value;
  28.             } else {
  29.                 mp1[key1] = value;
  30.             }
  31.         }
  32.     }
  33.  
  34.     // Получить значение по ключу первого типа.
  35.     // Генерирует исключение std::out_of_range("some text")
  36.     // в случае отсутствия ключа (как и функция at в std::map).
  37.     Value& GetByPrimaryKey(const Key1& key) {
  38.         try {
  39.             return mp1.at(key);
  40.         } catch (out_of_range ex) {}
  41.     }
  42.     const Value& GetByPrimaryKey(const Key1& key) const {
  43.         try {
  44.             return mp1.at(key);
  45.         } catch (out_of_range ex) {}
  46.     }
  47.  
  48.     // Аналогичная функция для ключа второго типа.
  49.     Value& GetBySecondaryKey(const Key2& key) {
  50.         try {
  51.             return mp2.at(key);
  52.         } catch (out_of_range ex) {}
  53.     }
  54.     const Value& GetBySecondaryKey(const Key2& key) const {
  55.         try {
  56.             return mp2.at(key);
  57.         } catch (out_of_range ex) {}
  58.     }
  59. };
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement