Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bimap.h"
- struct BiMap::Impl {
- Impl() {};
- Impl(const Impl& other) = default;
- Impl& operator=(const Impl& other) = default;
- bool Add(std::string_view key, std::string_view value) {
- // TODO: Реализуйте метод самостоятельно
- if (k2v_.find(key) != k2v_.end() || v2k_.find(value) != v2k_.end()) {
- return false;
- }
- try {
- dictionary_.push_back(key);
- v2k_[value] = dictionary_.back();
- dictionary_.push_back(value);
- k2v_[key] = dictionary_.back();
- } catch (std::bad_alloc& ba) {
- throw new std::bad_alloc;
- }
- return true;
- }
- std::optional<std::string_view> FindValue(std::string_view key) const noexcept {
- // TODO: Реализуйте метод самостоятельно
- try {
- return k2v_.at(key);
- }
- catch (std::out_of_range& oor) {
- return std::nullopt;
- }
- }
- std::optional<std::string_view> FindKey(std::string_view value) const noexcept {
- // TODO: Реализуйте метод самостоятельно
- try {
- return v2k_.at(value);
- }
- catch (std::out_of_range& oor) {
- return std::nullopt;
- }
- }
- private:
- std::deque<std::string_view> dictionary_;
- std::unordered_map<std::string_view, std::string_view> k2v_;
- std::unordered_map<std::string_view, std::string_view> v2k_;
- };
- BiMap::BiMap()
- : impl_(std::make_unique<Impl>()) {
- }
- BiMap::~BiMap() = default;
- BiMap::BiMap(BiMap&&) noexcept = default;
- BiMap& BiMap::operator=(BiMap&&) noexcept = default;
- BiMap::BiMap(const BiMap& other)
- : impl_(other.impl_ ? std::make_unique<Impl>(*other.impl_) : nullptr) {
- }
- BiMap& BiMap::operator=(const BiMap& other) {
- if (this != std::addressof(other)) {
- impl_ = std::make_unique<Impl>(*other.impl_);
- if (!other.impl_) { // Правый аргумент пуст?
- impl_.reset();
- } else if (impl_) { // Левый и правый аргументы не пустые?
- assert(other.impl_);
- *impl_ = *other.impl_;
- } else { // Левый аргумент пуст, а правый не пуст
- assert(!impl_ && other.impl_);
- }
- }
- return *this;
- }
- bool BiMap::Add(std::string_view key, std::string_view value) {
- return impl_->Add(key, value);
- }
- std::optional<std::string_view> BiMap::FindValue(std::string_view key) const noexcept {
- return impl_->FindValue(key);
- }
- std::optional<std::string_view> BiMap::FindKey(std::string_view value) const noexcept {
- return impl_->FindKey(value);
- }
Advertisement
Add Comment
Please, Sign In to add comment