Advertisement
Guest User

Untitled

a guest
Nov 27th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. //The generic map interface
  2. template <typename K, typename V>
  3. class Map
  4. {
  5. private:
  6.  
  7. //Make a reference class so we can enable [] operation
  8. class reference
  9. {
  10. public:
  11. //Enable the cast operation
  12. operator V const () { return map_.Find(key_); }
  13.  
  14. //enable the assignment operator
  15. reference& operator=(const V& val) { map_.Add(key_, val); return *this; }
  16. reference& operator=(const reference& ref) { *this = (V&) ref; return *this; }
  17.  
  18. private:
  19. reference (Map& map, const K key) : map_(map), key_(key) {}
  20. Map& map_;
  21. K key_;
  22. friend class Map;
  23. };
  24.  
  25. public:
  26. Map() : hash_(NULL), size_(0) { }
  27.  
  28. void SetHashStrategy(int hash_type = HashType::SIMPLE_HASH);
  29. void SetCollisionStrategy(int collision_method = CollisionType::CHAINING);
  30. void SetDataStructureStrategy(int data_structure_types = DSType::DYNAMIC_MAP);
  31. virtual ~Map()
  32. {
  33. Empty();
  34. delete hash_;
  35. delete ds_;
  36. }
  37.  
  38. //Interface functions
  39. void Add(K key,V value) { ++size_; ds_->Add(key, value); }
  40. void Remove(K key) { --size_; ds_->Remove(key); }
  41. V& Find(K key) { return ds_->Find(key); }
  42. size_t Size() { return size_; }
  43. void Empty() { size_ = 0; ds_->Empty(); }
  44.  
  45. //Square bracket access
  46. reference operator[] (const K& key) { return (reference(*this, key)); }
  47.  
  48. //Provide printing
  49. friend std::ostream& operator<< (std::ostream& o, const V& v) { return o << v; }
  50.  
  51. private:
  52. HashType* hash_;
  53. DataStructureType<K,V>* ds_;
  54. size_t size_;
  55. };
  56.  
  57. template <class K, class V>
  58. void Map<K,V>::SetHashStrategy(int hash_type)
  59. {
  60. if(hash_ == NULL)
  61. {
  62. delete hash_;
  63. }
  64.  
  65. if(hash_type == HashType::SIMPLE_HASH)
  66. {
  67. hash_ = new SimpleHash;
  68. }
  69. else if(hash_type == HashType::MD5_HASH)
  70. {
  71. hash_ = new MD5Hash;
  72. }
  73. }
  74.  
  75. template <class K, class V>
  76. void Map<K,V>::SetDataStructureStrategy(int ds_type)
  77. {
  78. if(ds_ == NULL)
  79. {
  80. delete ds_;
  81. }
  82.  
  83. if(ds_type == DSType::DYNAMIC_MAP)
  84. {
  85. ds_ = new DynamicMap<K,V>;
  86. }
  87. else if(ds_type == DSType::ARRAY_MAP)
  88. {
  89. ds_ = new ArrayMap<K,V>;
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement