赞
踩
LRU是Least Recently Used的缩写,即最近最少使用,常用于页面置换算法,是为虚拟页式存储管理服务的。
- #include<iostream>
- #include<list>
- #include<map>
-
- using namespace std;
-
- struct Node{
- int key;
- int value;
- Node(int k,int v):key(k),value(v){}
- };
- class LRUCache{
- private:
- int maxSize; //缓存的最大容量
- list<Node> cacheList; //用链表保存key的访问顺序,最近访问的Node在链表最前面
- map<int,list<Node>::iterator> mp;//用map储存key和链表的迭代器,方便快速查询key是否存在
- public:
- LRUCache(int capacity):maxSize(capacity){}
-
- int get(int key){
- map<int,list<Node>::iterator>::iterator it = mp.find(key);
- if(it==mp.end()) //NOT Found
- return -1;
- else{ //Found ,and update node to the front
- list<Node>::iterator listIter = mp[key];
- Node newNode(key,listIter->value);
- cacheList.erase(listIter);
- cacheList.push_front(newNode);
- mp[key] = cacheList.begin();
- }
- return mp[key]->value;
- }
-
- void set(int key,int value)
- {
- map<int,list<Node>::iterator>::iterator it = mp.find(key);
- if(it==mp.end())
- {
- if(cacheList.size() == maxSize)
- {
- mp.erase(cacheList.back().key);
- cacheList.pop_back();
- }
- Node newNode(key,value);
- cacheList.push_front(newNode);
- mp[key]=cacheList.begin();
- }
- else
- {
- list<Node>::iterator listIter = mp[key];
- Node newNode(key,value);
- cacheList.erase(listIter);
- cacheList.push_front(newNode);
- mp[key] = cacheList.begin();
- }
- }
-
- void print(){
-
- cout<<"LRUCache :"<<endl;
- for(auto listIter = cacheList.begin();listIter!=cacheList.end();listIter++)
- cout<<"Line "<< listIter->key<<" "<<listIter->value<<endl;
- }
-
- };
-
-
测试:
- int main()
- {
- LRUCache LRU(5);
- cout<<"输入地址k,值v"<<endl;
- int k,v;
- while((cin>>k,k>0))
- {
- cin>>v;
-
- LRU.set(k,v);
-
- LRU.print();
- }
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。