#pragma once /* Copyright (c) 2017 Swarthmore College Computer Science Department, Swarthmore PA A. Danner, M. Gagne, J. Brody, Z. Palmer, A. Soni Distributed as course material for Fall 2017 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 STLDictionary : 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> m_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: STLDictionary() { } private: STLDictionary(const STLDictionary& other) = delete; STLDictionary& operator=(const STLDictionary& other) = delete; }; template <typename K, typename V> int STLDictionary<K,V>::getSize() { return m_actualDictionary.size(); } template <typename K, typename V> bool STLDictionary<K,V>::isEmpty() { return m_actualDictionary.empty(); } template <typename K, typename V> void STLDictionary<K,V>::insert(K key, V value) { if (contains(key)) { throw runtime_error("STLDictionary::insert: key already present"); } m_actualDictionary[key] = value; } template <typename K, typename V> void STLDictionary<K,V>::update(K key, V value) { if (!contains(key)) { throw runtime_error("STLDictionary::update: key not present"); } m_actualDictionary[key] = value; } template <typename K, typename V> V STLDictionary<K,V>::get(K key) { if (!contains(key)) { throw runtime_error("STLDictionary::get: key not present"); } return m_actualDictionary[key]; } template <typename K, typename V> bool STLDictionary<K,V>::contains(K key) { try { m_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 STLDictionary<K,V>::remove(K key) { if (!contains(key)) { throw runtime_error("STLDictionary::remove: key not present"); } m_actualDictionary.erase(key); } template <typename K, typename V> std::vector<K> STLDictionary<K,V>::getKeys() { vector<K> vec; for (auto it = m_actualDictionary.begin(); it != m_actualDictionary.end(); it++) { vec.push_back(it->first); } return vec; } template <typename K, typename V> std::vector<pair<K,V>> STLDictionary<K,V>::getItems() { vector<pair<K,V>> vec; for (auto it = m_actualDictionary.begin(); it != m_actualDictionary.end(); it++) { vec.push_back(pair<K,V>(it->first, it->second)); } return vec; }