当前位置:   article > 正文

LRU调度算法: C++实现_lru页面调度算法c++实现

lru页面调度算法c++实现

LRU是Least Recently Used的缩写,即最近最少使用,常用于页面置换算法,是为虚拟页式存储管理服务的。

  1. #include<iostream>
  2. #include<list>
  3. #include<map>
  4. using namespace std;
  5. struct Node{
  6. int key;
  7. int value;
  8. Node(int k,int v):key(k),value(v){}
  9. };
  10. class LRUCache{
  11. private:
  12. int maxSize; //缓存的最大容量
  13. list<Node> cacheList; //用链表保存key的访问顺序,最近访问的Node在链表最前面
  14. map<int,list<Node>::iterator> mp;//用map储存key和链表的迭代器,方便快速查询key是否存在
  15. public:
  16. LRUCache(int capacity):maxSize(capacity){}
  17. int get(int key){
  18. map<int,list<Node>::iterator>::iterator it = mp.find(key);
  19. if(it==mp.end()) //NOT Found
  20. return -1;
  21. else{ //Found ,and update node to the front
  22. list<Node>::iterator listIter = mp[key];
  23. Node newNode(key,listIter->value);
  24. cacheList.erase(listIter);
  25. cacheList.push_front(newNode);
  26. mp[key] = cacheList.begin();
  27. }
  28. return mp[key]->value;
  29. }
  30. void set(int key,int value)
  31. {
  32. map<int,list<Node>::iterator>::iterator it = mp.find(key);
  33. if(it==mp.end())
  34. {
  35. if(cacheList.size() == maxSize)
  36. {
  37. mp.erase(cacheList.back().key);
  38. cacheList.pop_back();
  39. }
  40. Node newNode(key,value);
  41. cacheList.push_front(newNode);
  42. mp[key]=cacheList.begin();
  43. }
  44. else
  45. {
  46. list<Node>::iterator listIter = mp[key];
  47. Node newNode(key,value);
  48. cacheList.erase(listIter);
  49. cacheList.push_front(newNode);
  50. mp[key] = cacheList.begin();
  51. }
  52. }
  53. void print(){
  54. cout<<"LRUCache :"<<endl;
  55. for(auto listIter = cacheList.begin();listIter!=cacheList.end();listIter++)
  56. cout<<"Line "<< listIter->key<<" "<<listIter->value<<endl;
  57. }
  58. };

测试:

  1. int main()
  2. {
  3. LRUCache LRU(5);
  4. cout<<"输入地址k,值v"<<endl;
  5. int k,v;
  6. while((cin>>k,k>0))
  7. {
  8. cin>>v;
  9. LRU.set(k,v);
  10. LRU.print();
  11. }
  12. return 0;
  13. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/163722
推荐阅读
相关标签
  

闽ICP备14008679号