#pragma once /* Copyright (c) 2018 Swarthmore College Computer Science Department, Swarthmore PA A. Danner, M. Gagne, J. Brody, Z. Palmer, A. Soni, L. Meeden Distributed as course material for Spring 2018 CPSC 035: Data Structures and Algorithms */ #include <map> #include <stdexcept> #include <vector> #include <cs35/dictionary.h> using std::map; using std::runtime_error; using std::vector; template <typename K, typename V> class STLBBST : public Dictionary<K,V> { public: int getSize(); bool isEmpty(); void insert(K key, V value); void update(K key, V value); V get(K key); bool contains(K key); void remove(K key); std::vector<K> getKeys(); std::vector<pair<K,V>> getItems(); private: map<K,V> actualDictionary; // You can safely ignore the following code. This eliminates some default // class routines, preventing you from using them accidentally. // Specifically, we are disabling the use of the copy constructor and the // copy assignment operator. You can read more here: // http://www.cplusplus.com/articles/y8hv0pDG/ public: STLBBST() { } private: STLBBST(const STLBBST& other) = delete; STLBBST& operator=(const STLBBST& other) = delete; }; template <typename K, typename V> int STLBBST<K,V>::getSize() { return this->actualDictionary.size(); } template <typename K, typename V> bool STLBBST<K,V>::isEmpty() { return this->actualDictionary.empty(); } template <typename K, typename V> void STLBBST<K,V>::insert(K key, V value) { if (contains(key)) { throw runtime_error("STLBBST::insert: key already present"); } this->actualDictionary[key] = value; } template <typename K, typename V> void STLBBST<K,V>::update(K key, V value) { if (!contains(key)) { throw runtime_error("STLBBST::update: key not present"); } this->actualDictionary[key] = value; } template <typename K, typename V> V STLBBST<K,V>::get(K key) { if (!contains(key)) { throw runtime_error("STLBBST::get: key not present"); } return this->actualDictionary[key]; } template <typename K, typename V> bool STLBBST<K,V>::contains(K key) { try { this->actualDictionary.at(key); // check to see if the key exists return true; } catch (std::out_of_range& e) { return false; } } template <typename K, typename V> void STLBBST<K,V>::remove(K key) { if (!contains(key)) { throw runtime_error("STLBBST::remove: key not present"); } this->actualDictionary.erase(key); } template <typename K, typename V> vector<K> STLBBST<K,V>::getKeys() { vector<K> vec; for (auto it = this->actualDictionary.begin(); it != this->actualDictionary.end(); it++) { vec.push_back(it->first); } return vec; } template <typename K, typename V> vector<pair<K,V>> STLBBST<K,V>::getItems() { vector<pair<K,V>> vec; for (auto it = this->actualDictionary.begin(); it != this->actualDictionary.end(); it++) { vec.push_back(pair<K,V>(it->first, it->second)); } return vec; }