LRU缓存的简单示例c ++实现,结合了hash(unordered_map)和list

概要

实现了LRU缓存,结合了unordered_maplist数据结构,确保在插入、访问和淘汰元素时保持最近最少使用策略。

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缓存的流程图,展示了插入、获取和淘汰元素的流程:

Yes
No
Cache Full
Cache Not Full
Start
Key Exists?
Update Value
Check Cache Size
Evict LRU Item
Insert New Item
Move Item to Front
End

解释流程图步骤:

  1. 开始:开始执行LRU缓存操作。
  2. Key Exists?:检查待操作的键是否存在于缓存中。
    • Yes:如果键已存在,则执行更新值的操作。
    • No:如果键不存在,则继续检查缓存大小。
  3. Check Cache Size:检查缓存当前大小。
    • Cache Full:如果缓存已满,则执行淘汰最近最少使用的元素。
    • Cache Not Full:如果缓存未满,则直接插入新的键值对。
  4. Update Value:更新现有键对应的值。
  5. Evict LRU Item:从缓存中移除最近最少使用的元素。
  6. Insert New Item:将新的键值对插入到缓存中。
  7. Move Item to Front:将访问的元素移动到缓存链表的头部,以表示最近使用。
  8. End:结束当前操作,等待下一个操作。

这样的实现结合了哈希表和双向链表,确保了在常数时间内(O(1))执行插入、更新和获取操作,同时保持了LRU缓存的特性。

参考

lru-cache-design

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘色的喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值