LRU(Least Recently Used)缓存是一种常用的缓存淘汰算法,它在有限的缓存空间中保留最近使用过的数据,而淘汰最久未使用的数据。一个高效的LRU缓存实现需要满足以下要求:
- 快速的查找操作(O(1)时间复杂度)
- 快速的插入和删除操作(O(1)时间复杂度)
- 能够跟踪元素的使用顺序
为了满足这些要求,我们可以使用以下STL容器:
- std::unordered_map:用于快速查找键值对
- std::list:用于维护元素的使用顺序
下面是详细的C++实现,包括注释:
#include <iostream>
#include <unordered_map>
#include <list>
template<typename Key, typename Value>
class LRUCache {
private:
using KeyValuePair = std::pair<Key, Value>;
using ListIterator = typename std::list<KeyValuePair>::iterator;
int capacity;
std::list<KeyValuePair> items;
std::unordered_map<Key, ListIterator> cache;
public:
LRUCache(int cap) : capacity(cap) {}
// 获取缓存中的值,如果存在则将其移到最近使用的位置
Value get(const Key& key) {
auto it = cache.find(key);
if (it == cache.end()) {
return Value(); // 如果key不存在,返回默认值
}
// 将访问的元素移到列表前端
items.splice(items.begin(), items, it->second);
return it->second->second;
}
// 向缓存中插入或更新一个键值对
void put(const Key& key, const Value& value) {
auto it = cache.find(key);
if (it != cache.end()) {
// 如果key已存在,更新值并移到列表前端
it->second->second = value;
items.splice(items.begin(), items, it->second);
} else {
// 如果缓存已满,删除最久未使用的元素
if (cache.size() == capacity) {
cache.erase(items.back().first);
items.pop_back();
}
// 在列表前端插入新元素
items.push_front({key, value});
cache[key] = items.begin();
}
}
// 打印当前缓存内容(用于调试)
void printCache() const {
for (const auto& item : items) {
std::cout << item.first << ": " << item.second << " | ";
}
std::cout << std::endl;
}
};
// 测试LRU缓存
int main() {
LRUCache<int, std::string> cache(3);
cache.put(1, "one");
cache.put(2, "two");
cache.put(3, "three");
cache.printCache(); // 输出:3: three | 2: two | 1: one |
std::cout << "Get 2: " << cache.get(2) << std::endl; // 输出:Get 2: two
cache.printCache(); // 输出:2: two | 3: three | 1: one |
cache.put(4, "four");
cache.printCache(); // 输出:4: four | 2: two | 3: three |
std::cout << "Get 1: " << cache.get(1) << std::endl; // 输出:Get 1:
cache.printCache(); // 输出:4: four | 2: two | 3: three |
return 0;
}
这个实现的关键点包括:
- 使用std::unordered_map存储键到列表迭代器的映射,实现O(1)的查找。
- 使用std::list存储键值对,维护使用顺序。
- 在get操作中,如果找到key,将对应的元素移到列表前端(最近使用)。
- 在put操作中,如果key已存在,更新值并移到列表前端;如果key不存在且缓存已满,删除列表尾部(最久未使用)的元素,然后在前端插入新元素。
这个设计的优点:
- 查找、插入和删除操作都是O(1)时间复杂度。
- 使用STL容器,代码简洁且易于理解。
- 通过模板实现,可以适用于不同类型的键和值。
在博客中,您可以进一步讨论:
- LRU缓存的应用场景(如数据库缓存、网页缓存等)。
- 与其他缓存策略(如FIFO、LFU)的比较。
- 如何进行性能优化和线程安全处理。
- 在实际项目中使用LRU缓存的最佳实践。
这个实现为读者提供了一个清晰、高效的LRU缓存示例,可以作为理解缓存算法和STL使用的良好起点。