- LRU算法的设计原则是:如果一个数据在最近一段时间没有被访问到,那么在将来它被访问的可能性也很小。也就是说,当限定的空间已存满数据时,应当把最久没有被访问到的数据淘汰。
- 实现思想:用list保存数据,用unodered_map保存指向list的指针(方便定位查找),和一个数据量的最大值
- 代码如下:
#include<iostream> #include<functional> #include<list> #include<unordered_map> using namespace std; /* * File: lrucache.hpp * Author: Alexander Ponomarev * * Created on June 20, 2013, 5:09 PM */ template<typename key_t, typename value_t> class lru_cache { public: typedef typename std::pair<key_t, value_t> key_value_pair_t; typedef typename std::list<key_value_pair_t>::iterator list_iterator_t; lru_cache(size_t max_size) : _max_size(max_size) { } void put(const key_t& key, const value_t& value) { auto it = _cache_items_map.find(key); _cache_items_list.push_front(key_value_pair_t(key, value)); if (it != _cache_items_map.end()) { _cache_items_l
LRU算法--作为缓存
最新推荐文章于 2022-03-15 12:44:06 发布
LRU算法基于最近最少使用原则,用于缓存淘汰。当缓存满时,会淘汰最近最少使用的数据。实现通常结合list和unordered_map,提供快速查找和定位。代码实现后,运行展示缓存操作结果。此外,还提及了其他缓存算法如FIFO和LFU。
摘要由CSDN通过智能技术生成