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

#include
#include
#include
#include
#include
#include
#include
#include
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().value);//根据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::iterator it = mylist.begin();
		while (it != mylist.end()){
			cout << it->value << " ";
			it++;
		}
		cout << endl;
	}
private:
	int mycapacity;
	list mylist;
	hash_map::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 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;
}

 

你可能感兴趣的:(算法)