LRU页面置换算法的C++模拟实现

#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
#include<hash_map>
#include<list>
#include<assert.h>
using namespace std;


//O(1)
struct Node{
	int key;
	int value;
	Node(int k, int v) :key(k), value(v){}
};

class LRUCache {
public:
	LRUCache(int capacity) {
		mycapacity = capacity;
	}

	int get(int key) {
		if (myhashmap.find(key) != myhashmap.end()){
			mylist.splice(mylist.begin(),mylist,myhashmap[key]);
			myhashmap[key] = mylist.begin();
			return myhashmap[key]->value;
		}
		return -1;
	}

	void put(int key, int value) {
		if (myhashmap.find(key) == myhashmap.end()){ //不在页中
			if (mylist.size() == mycapacity){//不在页中且页满
				myhashmap.erase(mylist.back().key);//根据list上最后一个节点的值在hash_map中删除
				mylist.pop_back();//链表删除
			}
			mylist.push_front(Node(key,value));//将该新节点插入链表中并
			myhashmap[key] = mylist.begin();//更新hash_map
		}
		else{  //在页中
			myhashmap[key]->value = value;
			mylist.splice(mylist.begin(),mylist,myhashmap[key]);//将该节点放置在队首
			myhashmap[key] = mylist.begin();//更新hash_map
		}
	}
	void Show(){
		list<Node>::iterator it = mylist.begin();
		while (it != mylist.end()){
			cout << it->value << " ";
			it++;
		}
		cout << endl;
	}
private:
	int mycapacity;
	list<Node> mylist;
	hash_map<int, list<Node>::iterator> myhashmap;
};

int main(){
	LRUCache lr(3);
	lr.put(1,7);
	lr.Show();
	lr.put(2,0);
	lr.Show();
	lr.put(3,1);
	lr.Show();
	lr.put(4,2);
	lr.Show();
	lr.put(5,0);
	lr.Show();
	lr.put(6, 3);
	lr.Show();
	return 0;
}




struct PageIn{
	int count;
	int page;
};
int main(){

	int len;
	cin >> len;
	vector<PageIn> vec;
	while (true){
		int tmp;
		cin >> tmp;
		//页满
		if (vec.size() >= len){
			int maxcount = vec[0].count;  //记录最近最久未使用的  也就是count最大的
			bool jud = false;  //判断是否是之前已有页面 如果有将标志置为true 若为false就需要与count最大的页面置换
			for (int j = 0; j < len; j++){
				if (tmp == vec[j].page){
					vec[j].count = 0;
					jud = true;
				}

				else{
					vec[j].count++;  //不在页面中 当前页面计数++
				}
				if (vec[j].count > maxcount){
					maxcount = vec[j].count;
				}
			}
			//不在页面中根据最大count置换页面 将新的页计数置为0
			if (!jud){
				for (int k = 0; k < len; k++){
					if (vec[k].count == maxcount){
						vec[k].page = tmp;
						vec[k].count = 0;
					}
				}
			}
		}
		//页面没有满 
		else{
			//之前的页引用时间count++
			for (int i = 0; i < vec.size(); i++){
				if (vec[i].page != tmp){
					vec[i].count++;
				}
			}
			//插入新的 引用计数为0
			struct PageIn tr;
			tr.count = 0;
			tr.page = tmp;
			vec.push_back(tr);
		}
		for (int i = 0; i < vec.size(); i++){
			cout << vec[i].page << " ";
		}
		cout << endl;
	}
	return 0;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值