LRU缓存设计(三)

2014-11-24 00:58:12 · 作者: · 浏览: 21

if (_map.size() >= _maxsize) {
Val * old_lru = _lru;
if (_lru->second._newer) {
_lru = _lru->second._newer;
_lru->second._older = NULL;
}
_map.erase(old_lru->first);
}


// insert key to MRU position
std::pair ret
= _map.insert( Val(key, LRUCacheH4Value(V(), _mru, NULL)) );


Val * inserted = &*ret.first;
if (_mru)
_mru->second._newer = inserted;
_mru = inserted;


// possibly update the LRU
if (!_lru)
_lru = _mru;
else if (!_lru->second._newer)
_lru->second._newer = _mru;


return inserted;
}



} // namespace lru


测试代码:


#include


#include "lru.hpp"


using namespace lru;
using namespace std;


int main()
{
typedef LRUCacheH4 CacheType;


CacheType tc(3);


tc.insert(1, 101);
tc.insert(2, 102);
tc.insert(3, 103);

tc.insert(2, 1002);


cout << tc[1] << endl;


cout << "================" << endl;


for (CacheType::const_iterator it = tc.mru_begin(); it != tc.end(); ++it)
cout << it.key() << " " << it.value() << endl;


cout << "================" << endl;


for (CacheType::const_iterator it = tc.lru_begin(); it != tc.end(); ++it)
cout << it.key() << " " << it.value() << endl;


system("PAUSE");
return 0;
}