Punchcard

BiMap working

Mar 26th, 2024
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.37 KB | Source Code | 0 0
  1. //  bimap.cpp
  2.  
  3. #include "bimap.h"
  4.  
  5. struct BiMap::Impl {   
  6.  
  7.     Impl() {};    
  8.     Impl(const Impl& other) = default;
  9.     Impl& operator=(const Impl& other) = default;
  10.    
  11.     bool Add(std::string_view key, std::string_view value) {
  12.         // TODO: Реализуйте метод самостоятельно
  13.         if (k2v_.find(key) != k2v_.end() || v2k_.find(value) != v2k_.end()) {
  14.             return false;
  15.         }        
  16.         try {          
  17.             dictionary_.emplace_back(value);
  18.             std::string_view val_ref = dictionary_.back();
  19.            
  20.             dictionary_.emplace_back(key);
  21.             std::string_view key_ref = dictionary_.back();
  22.            
  23.             v2k_.emplace(val_ref, key_ref);    
  24.             k2v_.emplace(key_ref, val_ref);        
  25.  
  26.         } catch (std::bad_alloc& ba) {
  27.             throw new std::bad_alloc;
  28.         }
  29.         return true;
  30.     }
  31.  
  32.     std::optional<std::string_view> FindValue(std::string_view key) const noexcept {
  33.         // TODO: Реализуйте метод самостоятельно
  34.         try {
  35.             return k2v_.at(key);
  36.         }
  37.         catch (std::out_of_range& oor) {
  38.             return std::nullopt;
  39.         }
  40.     }
  41.  
  42.     std::optional<std::string_view> FindKey(std::string_view value) const noexcept {
  43.         // TODO: Реализуйте метод самостоятельно
  44.         try {
  45.             return v2k_.at(value);
  46.         }      
  47.         catch (std::out_of_range& oor) {
  48.             return std::nullopt;
  49.         }
  50.     }
  51. private:
  52.     std::deque<std::string> dictionary_;
  53.     std::unordered_map<std::string_view, std::string_view> k2v_;
  54.     std::unordered_map<std::string_view, std::string_view> v2k_;
  55. };
  56.  
  57. BiMap::BiMap()
  58.     : impl_(std::make_unique<Impl>()) {
  59. }
  60.  
  61. BiMap::~BiMap() = default;
  62.  
  63. BiMap::BiMap(BiMap&&) noexcept = default;
  64.  
  65. BiMap& BiMap::operator=(BiMap&&) noexcept = default;
  66.  
  67. BiMap::BiMap(const BiMap& other)
  68.     : impl_(other.impl_ ? std::make_unique<Impl>(*other.impl_) : nullptr) {
  69. }
  70.  
  71. BiMap& BiMap::operator=(const BiMap& other) {
  72.     if (this != std::addressof(other)) {
  73.         impl_ = std::make_unique<Impl>(*other.impl_);
  74.         if (!other.impl_) {     // Правый аргумент пуст?
  75.             impl_.reset();
  76.         } else if (impl_) {     // Левый и правый аргументы не пустые?
  77.             assert(other.impl_);
  78.             *impl_ = *other.impl_;
  79.         } else {                // Левый аргумент пуст, а правый не пуст
  80.             assert(!impl_ && other.impl_);            
  81.         }
  82.     }
  83.     return *this;
  84. }
  85.  
  86. bool BiMap::Add(std::string_view key, std::string_view value) {
  87.     return impl_->Add(key, value);
  88. }
  89.  
  90. std::optional<std::string_view> BiMap::FindValue(std::string_view key) const noexcept {
  91.     return impl_->FindValue(key);
  92. }
  93.  
  94. std::optional<std::string_view> BiMap::FindKey(std::string_view value) const noexcept {
  95.     return impl_->FindKey(value);
  96. }
  97.  
  98. // bimap.h
  99. #pragma once
  100. #include <optional>
  101. #include <string>
  102. #include <string_view>
  103. #include <unordered_map>
  104. #include <deque>
  105. #include <memory>
  106. #include <stdexcept>
  107. #include <cassert>
  108.  
  109. class BiMap {
  110. public:
  111.     /**
  112.      * Добавляет в словарь пару "ключ-значение".
  113.      * В случае успеха возвращает true.
  114.      * Возвращает false, если ключ или значение были ранее добавлены.
  115.      *
  116.      * Метод обеспечивает строгую гарантию безопасности исключений
  117.      */
  118.     BiMap();
  119.     ~BiMap();
  120.     BiMap(BiMap&&) noexcept;
  121.     BiMap& operator=(BiMap&&) noexcept;
  122.     BiMap(const BiMap& other);
  123.     BiMap& operator=(const BiMap& other);
  124.    
  125.     bool Add(std::string_view key, std::string_view value);
  126.  
  127.     /**
  128.      * Возвращает значение, связанное с ключом, либо nullopt, если такого ключа нет
  129.      */
  130.     std::optional<std::string_view> FindValue(std::string_view key) const noexcept;
  131.  
  132.     /**
  133.      * Возвращает ключ, связанный с value, либо nullopt, если такого значения нет
  134.      */
  135.     std::optional<std::string_view> FindKey(std::string_view value) const noexcept;
  136.  
  137. private:
  138.     /* Класс должен использовать идиому Pimpl, поддерживать копирование и перемещение */
  139.     struct Impl;
  140.     // unique_ptr автоматически удалит связанные с классом данные
  141.     std::unique_ptr<Impl> impl_;   
  142. };
Advertisement
Add Comment
Please, Sign In to add comment