Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //The generic map interface
- template <typename K, typename V>
- class Map
- {
- private:
- //Make a reference class so we can enable [] operation
- class reference
- {
- public:
- //Enable the cast operation
- operator V const () { return map_.Find(key_); }
- //enable the assignment operator
- reference& operator=(const V& val) { map_.Add(key_, val); return *this; }
- reference& operator=(const reference& ref) { *this = (V&) ref; return *this; }
- private:
- reference (Map& map, const K key) : map_(map), key_(key) {}
- Map& map_;
- K key_;
- friend class Map;
- };
- public:
- Map() : hash_(NULL), size_(0) { }
- void SetHashStrategy(int hash_type = HashType::SIMPLE_HASH);
- void SetCollisionStrategy(int collision_method = CollisionType::CHAINING);
- void SetDataStructureStrategy(int data_structure_types = DSType::DYNAMIC_MAP);
- virtual ~Map()
- {
- Empty();
- delete hash_;
- delete ds_;
- }
- //Interface functions
- void Add(K key,V value) { ++size_; ds_->Add(key, value); }
- void Remove(K key) { --size_; ds_->Remove(key); }
- V& Find(K key) { return ds_->Find(key); }
- size_t Size() { return size_; }
- void Empty() { size_ = 0; ds_->Empty(); }
- //Square bracket access
- reference operator[] (const K& key) { return (reference(*this, key)); }
- //Provide printing
- friend std::ostream& operator<< (std::ostream& o, const V& v) { return o << v; }
- private:
- HashType* hash_;
- DataStructureType<K,V>* ds_;
- size_t size_;
- };
- template <class K, class V>
- void Map<K,V>::SetHashStrategy(int hash_type)
- {
- if(hash_ == NULL)
- {
- delete hash_;
- }
- if(hash_type == HashType::SIMPLE_HASH)
- {
- hash_ = new SimpleHash;
- }
- else if(hash_type == HashType::MD5_HASH)
- {
- hash_ = new MD5Hash;
- }
- }
- template <class K, class V>
- void Map<K,V>::SetDataStructureStrategy(int ds_type)
- {
- if(ds_ == NULL)
- {
- delete ds_;
- }
- if(ds_type == DSType::DYNAMIC_MAP)
- {
- ds_ = new DynamicMap<K,V>;
- }
- else if(ds_type == DSType::ARRAY_MAP)
- {
- ds_ = new ArrayMap<K,V>;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement