1: #include <map>
   2: #include <string>
   3: #include <iostream>
using namespace std;
   5:  
   6:  template<class K, class V>
public map<K, V> 
   8:  {
   9:      typedef map<K, V> base_type;
timestamp;
timestamp> K2T;
timestamp, K> T2K;
  13:   
// from key to timestamp
// from timestamp to key
  16:   
timestamp tm;
  18:      size_type capacity;
  19:      lrumap(size_type cap=10)
  20:          : tm(1), capacity(cap) {}
  21:   
  22:      V& operator[](const K& k)
  23:      {
timestamp& _tm=k2t[k];
// if the timestamp already exist, delete it from t2k
  26:              t2k.erase(_tm);
// update timestamp in k2t
// update key in t2k
  29:   
  30:          V& ret= base_type::operator[](k);
  31:   
// remove the oldest if necessary
  33:          if(size()>capacity)
  34:          {
// get the eldest key
  36:              erase(k);
  37:          }
  38:          return ret;
  39:      }
  40:      void erase(const K& k)
  41:      {
// erase timestamp <-> key reference
  43:          t2k.erase(k2t[k]);
  44:          k2t.erase(k);
// then the actual data
  46:          base_type::erase(k);
  47:      }
  48:  };

相关文章: