下面是一个简单的LRU缓存的C++实现:
#include <iostream>
#include <unordered_map>
#include <list>
class LRUCache {
private:
int capacity;
std::unordered_map<int, std::pair<int, std::list<int>::iterator>> cache;
std::list<int> lruList;
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (cache.find(key) != cache.end()) {
updateLRU(key);
return cache[key].first;
}
return -1;
}
void put(int key, int value) {
if (cache.find(key) == cache.end()) {
// 判断缓存是否已满
if (cache.size() >= capacity) {
// 删除最久未使用的键
int oldestKey = lruList.back();
lruList.pop_back();
cache.erase(oldestKey);
}
// 插入新键
lruList.push_front(key);
} else {
// 更新已存在的键的值
updateLRU(key);
}
cache[key] = {value, lruList.begin()};
}
private:
void updateLRU(int key) {
auto it = cache[key].second;
lruList.erase(it);
lruList.push_front(key);
cache[key].second = lruList.begin();
}
};
int main() {
LRUCache cache(2);
// 测试例子
cache.put(1, 10);
cache.put(2, 20);
std::cout << "Value of key 1: " << cache.get(1) << std::endl; // 输出: 10
cache.put(3, 30); // 缓存容量已满,移除最久未使用的键 2
std::cout << "Value of key 2: " << cache.get(2) << std::endl; // 输出: -1
cache.put(4, 40); // 缓存容量已满,移除最久未使用的键 1
std::cout << "Value of key 1: " << cache.get(1) << std::endl; // 输出: -1
std::cout << "Value of key 3: " << cache.get(3) << std::endl; // 输出: 30
std::cout << "Value of key 4: " << cache.get(4) << std::endl; // 输出: 40
return 0;
}
这是一个简单的LRU缓存实现,通过哈希表和双向链表实现了快速查找和LRU淘汰策略。其中,哈希表用于记录每个键对应的值以及在双向链表中的位置,而双向链表用于维护访问顺序。在插入新键或更新已存在的键时,会将该键移动到链表头部,并更新其在哈希表中的位置。当缓存容量超过设定值时,会移除链表尾部(即最久未使用)的键。
以上代码仅为简化实现,请根据需要进行适当扩展和改进。
内容由零声教学AI助手提供,问题来源于学员提问




