LRU调度算法: C++实现

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值