【c++程序】LRU缓存算法

LRU Cache是一个Cache的置换算法,含义是“最近最少使用”,把满足“最近最少使用”的数据从Cache中剔除出去,

并且保证Cache中第一个数据是最近刚刚访问的,因为这样的数据更有可能被接下来的程序所访问。

#include <iostream>
#include <vector>
using namespace std;
int lruCountMiss(int max,int *page,int len)
{
	vector<int> shuzu;
	if(len<=max)
		return len;
	else
	{
	    shuzu.push_back(page[0]);
		int count = 1;
		bool find = false;
		for(int j = 0;j<len;j++)
		{
			for(int i = 0;i<shuzu.size();i++)
			{
				if(shuzu[i] == page[j])
				{
					shuzu.erase(shuzu.begin()+i);
					shuzu.push_back(page[j]);
					find = true;
				}
			}
			if(find == false)
			{
				count++;
				if(shuzu.size()< max)
					shuzu.push_back(page[j]);
				else
				{
					shuzu.erase(shuzu.begin());
				    shuzu.push_back(page[j]);
				}
			}
			find = false;
		}
		return count;
	}
}

int main()
{
	int page[16] = {7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0};
	cout<<lruCountMiss(3,page,16)<<endl;
	return 0;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LRU(Least Recently Used)是一种常见的页面置换算法,也可以用于缓存淘汰策略。在LRU算法中,缓存满时,会将最近最少使用的数据淘汰掉,以腾出空间存储新的数据。下面是一个C++实现的LRU缓存类的示例代码: ```c++ #include <iostream> #include <unordered_map> #include <list> using namespace std; class LRUCache { private: int capacity; unordered_map<int, pair<int, list<int>::iterator>> cache; list<int> lru; public: LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { if (cache.find(key) == cache.end()) { return -1; } // 将访问的元素移到链表头部 lru.erase(cache[key].second); lru.push_front(key); cache[key].second = lru.begin(); return cache[key].first; } void put(int key, int value) { if (cache.find(key) != cache.end()) { // 更新元素的值,并将其移到链表头部 lru.erase(cache[key].second); lru.push_front(key); cache[key] = {value, lru.begin()}; } else { if (cache.size() == capacity) { // 淘汰最近最少使用的元素 cache.erase(lru.back()); lru.pop_back(); } // 将新元素插入链表头部 lru.push_front(key); cache[key] = {value, lru.begin()}; } } void print() { for (auto it = lru.begin(); it != lru.end(); ++it) { cout << *it << " "; } cout << endl; } }; ``` 在上面的代码中,LRUCache类包含三个私有成员变量:capacity表示缓存的容量,cache是一个哈希表,用于存储键值对和对应的链表迭代器,lru是一个双向链表,用于存储键的访问顺序。LRUCache类提供了get和put两个公有方法,分别用于获取和插入元素。在get方法中,如果元素存在,则将其移到链表头部,并返回其值;否则返回-1。在put方法中,如果元素已存在,则更新其值,并将其移到链表头部;否则,如果缓存已满,则淘汰最近最少使用的元素,并将新元素插入链表头部。LRUCache类还提供了一个print方法,用于打印当前缓存中的所有键。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值