fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. template <class Key, class T, class Compare = std::less<Key>,
  7. class Allocator = std::allocator<std::pair<const Key,T> > >
  8. class mymap: public std::map<Key, T, Compare, Allocator>
  9. {
  10. public:
  11. typedef std::map<Key, T, Compare, Allocator> base;
  12.  
  13. explicit mymap(const Compare& comp = Compare(), const Allocator& alloc = Allocator()): base(comp, alloc), cache_valid_(false) {}
  14.  
  15. template <class InputIterator>
  16. mymap(InputIterator first, InputIterator last,
  17. const Compare & comp = Compare(), const Allocator & alloc = Allocator()): base(first, last, comp, alloc), cache_valid_(false) {}
  18.  
  19. mymap(const mymap<Key,T,Compare,Allocator> & x): base(x), cache_valid_(false) {}
  20.  
  21. mymap & operator = (mymap const & m) { base::operator = (m); cache_valid_(false); return *this; }
  22.  
  23. ~mymap() {
  24. std::cout << "Hello, lamer007, i'm non virtual destructor of custom map!" << std::endl;
  25. }
  26.  
  27. T & operator[] (Key const & key)
  28. {
  29. if (cache_valid_ && cached_->first == key) {
  30. std::cout << "cached value for [" << key << "]" << std::endl;
  31. return cached_->second;
  32. }
  33.  
  34. std::cout << "real value for [" << key << "]" << std::endl;
  35. cached_ = base::insert(std::make_pair(key, T())).first;
  36. cache_valid_ = true;
  37. return cached_->second;
  38. }
  39.  
  40. void reset_cache() { cache_valid_ = false; }
  41.  
  42. private:
  43. typename base::iterator cached_;
  44. bool cache_valid_;
  45. };
  46.  
  47.  
  48. int main()
  49. {
  50. {
  51. mymap<std::string, std::string> mm;
  52. mm["hello"] = "world";
  53.  
  54. if (mm["hello"] == "World" || mm["hello"] == "WORLD"
  55. || mm["world"] == "hello" || mm["hello"] == "w0rld"
  56. || mm["hello"] == "world")
  57. std::cout << "ok" << std::endl;
  58. else
  59. std::cout << "failed" << std::endl;
  60.  
  61. }
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0.02s 2864KB
stdin
Standard input is empty
stdout
real value for [hello]
cached value for [hello]
cached value for [hello]
real value for [world]
real value for [hello]
cached value for [hello]
ok
Hello, lamer007, i'm non virtual destructor of custom map!