概要
实现了LRU缓存,结合了unordered_map
和list
数据结构,确保在插入、访问和淘汰元素时保持最近最少使用策略。
C++实现:
#include <iostream>
#include <list>
#include <unordered_map>
#include <cassert>
using namespace std;
// Define a class for LRU Cache
template <class KEY_T, class VAL_T>
class LRUCache {
private:
// Define the list node structure
struct CacheNode {
KEY_T key;
VAL_T value;
CacheNode(KEY_T k, VAL_T v) : key(k), value(v) {}
};
// Define members: list for cache items, map for quick lookup, and cache size
list<CacheNode> cacheList;
unordered_map<KEY_T, typename list<CacheNode>::iterator> cacheMap;
size_t capacity;
public:
// Constructor to initialize the cache with given capacity
LRUCache(size_t capacity_) : capacity(capacity_) {}
// Function to retrieve value from cache based on key
VAL_T get(const KEY_T &key) {
// Check if key exists in cache
if (cacheMap.find(key) == cacheMap.end()) {
return VAL_T(); // Return default value if key not found (assuming VAL_T supports default constructor)
} else {
// Move accessed item to the front of the list
auto it = cacheMap[key];
cacheList.splice(cacheList.begin(), cacheList, it);
cacheMap[key] = cacheList.begin();
return it->value;
}
}
// Function to insert or update value in cache
void put(const KEY_T &key, const VAL_T &value) {
// Check if key already exists
if (cacheMap.find(key) != cacheMap.end()) {
// Key exists, update the value and move to front
auto it = cacheMap[key];
it->value = value;
cacheList.splice(cacheList.begin(), cacheList, it);
cacheMap[key] = cacheList.begin();
} else {
// Key doesn't exist, insert new item
if (cacheList.size() == capacity) {
// Cache is full, evict the least recently used item (from the end)
auto last = cacheList.back();
cacheMap.erase(last.key);
cacheList.pop_back();
}
// Insert new item to the front
cacheList.emplace_front(key, value);
cacheMap[key] = cacheList.begin();
}
}
// Function to check if key exists in cache
bool exists(const KEY_T &key) {
return cacheMap.find(key) != cacheMap.end();
}
// Function to print the current state of the cache (for debugging purposes)
void printCache() {
cout << "Current Cache State:" << endl;
for (auto &node : cacheList) {
cout << "(" << node.key << ": " << node.value << ") ";
}
cout << endl;
}
};
// Example usage
int main() {
LRUCache<int, int> cache(2); // Capacity is 2
cache.put(1, 1);
cache.put(2, 2);
cache.printCache(); // Output: (2: 2) (1: 1)
cout << cache.get(1) << endl; // Output: 1
cache.printCache(); // Output: (1: 1) (2: 2)
cache.put(3, 3); // evicts key 2
cache.printCache(); // Output: (3: 3) (1: 1)
cout << cache.get(2) << endl; // Output: 0 (not found)
cout << cache.get(3) << endl; // Output: 3
cache.put(4, 4); // evicts key 1
cache.printCache(); // Output: (4: 4) (3: 3)
cout << cache.get(1) << endl; // Output: 0 (not found)
cout << cache.get(3) << endl; // Output: 3
cout << cache.get(4) << endl; // Output: 4
return 0;
}
流程图:
下面是LRU缓存的流程图,展示了插入、获取和淘汰元素的流程:
解释流程图步骤:
- 开始:开始执行LRU缓存操作。
- Key Exists?:检查待操作的键是否存在于缓存中。
- Yes:如果键已存在,则执行更新值的操作。
- No:如果键不存在,则继续检查缓存大小。
- Check Cache Size:检查缓存当前大小。
- Cache Full:如果缓存已满,则执行淘汰最近最少使用的元素。
- Cache Not Full:如果缓存未满,则直接插入新的键值对。
- Update Value:更新现有键对应的值。
- Evict LRU Item:从缓存中移除最近最少使用的元素。
- Insert New Item:将新的键值对插入到缓存中。
- Move Item to Front:将访问的元素移动到缓存链表的头部,以表示最近使用。
- End:结束当前操作,等待下一个操作。
这样的实现结合了哈希表和双向链表,确保了在常数时间内(O(1))执行插入、更新和获取操作,同时保持了LRU缓存的特性。