#include <map>
#include <vector>
#include <iostream>
using namespace std;
template <typename Key, typename Value>
class LRUNode {
public:
Key key;
Value value;
class LRUNode<Key, Value> *prev, *next;
LRUNode() : prev(NULL), next(NULL) {}
LRUNode(Key k, Value v) : key(k), value(v), prev(NULL), next(NULL) {}
};
template <typename Key, typename Value>
class LRUCache {
private:
LRUNode<Key, Value> *first, *last;
vector<LRUNode<Key, Value> *> pool;
map<Key, LRUNode<Key, Value> *> exist;
void attach(LRUNode<Key, Value> *p) {
if (!first) first = last = p;
else {
p->prev = NULL;
p->next = first;
first->prev = p;
first = p;
}
}
void detach(LRUNode<Key, Value> *p) {
if (p->prev)
p->prev->next = p->next;
else
first = p->next;
if (p->next)
p->next->prev = p->prev;
else
last = p->prev;
}
public:
LRUCache(int size) : first(NULL), last(NULL) {
for (int i = 0;i < size;++i)
pool.push_back(new LRUNode<Key, Value>);
}
~LRUCache() {
LRUNode<Key, Value> *p;
while (!pool.empty())
pool.pop_back();
while (first) {
p = first->next;
delete first;
first = p;
}
}
void put(Key k, Value v) {
map<Key, LRUNode<Key, Value> *>::iterator iter;
iter = exist.find(k);
if (iter != exist.end()) {
iter->second->value = v;
detach(iter->second);
attach(iter->second);
} else {
LRUNode<Key, Value> *p;
if (!pool.empty()) {
p = pool.back();
pool.pop_back();
} else {
p = last;
exist.erase(p->key);
detach(p);
}
p->key = k;
p->value = v;
exist.insert(pair<Key, LRUNode<Key, Value> *>(k, p));
attach(p);
}
}
Value get(Key k) {
map<Key, LRUNode<Key, Value> *>::iterator iter;
if (first->key == k) return first->value;
iter = exist.find(k);
if (iter != exist.end()) {
detach(iter->second);
attach(iter->second);
return iter->second->value;
} else
return Value();
}
void print() {
LRUNode<Key, Value> *p = first;
while (p) {
cout<<int(p->key)<<" "<<int(p->value)<<endl;
p = p->next;
}
}
};
int main(int argc, char **argv)
{
LRUCache<int, int> lru(5);
lru.put(1, 100);
lru.put(2, 200);
lru.put(3, 300);
lru.put(4, 400);
lru.put(5, 500);
lru.print();
lru.put(6, 600);
lru.put(3, 300);
lru.put(4, 400);
lru.print();
int x;
cin>>x;
return 0;
}
C++ LRU Cache
最新推荐文章于 2024-06-21 00:01:38 发布