How to implement caching in c++?

Member

by ryleigh , in category: Third Party Scripts , a month ago

How to implement caching in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a month ago

@ryleigh 

Caching can be implemented in C++ by using data structures such as maps, unordered_maps, or custom cache data structures.


Here is an example of how to implement a simple cache using an unordered_map in C++:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <unordered_map>

class LRUCache {
private:
    std::unordered_map<int, int> cache;
    int capacity;

public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }

    int get(int key) {
        if (cache.find(key) != cache.end()) {
            // If key exists in cache, update its value and move it to the front
            int value = cache[key];
            cache.erase(key);
            cache[key] = value;
            return value;
        }
        return -1; // Return -1 if key is not found in cache
    }

    void put(int key, int value) {
        if (cache.find(key) != cache.end()) {
            cache.erase(key); // If key exists, update its value and move it to the front
        }
        cache[key] = value;

        // If cache size exceeds capacity, remove the least recently used key
        if (cache.size() > capacity) {
            auto it = cache.begin();
            cache.erase(it);
        }
    }
};


This example shows a simple implementation of a Least Recently Used (LRU) cache using an unordered_map in C++. The LRUCache class has methods to get and put key-value pairs in the cache, with a specified capacity. When an element is accessed or updated, it is moved to the front of the cache to indicate it was most recently used.


You can customize this implementation based on your specific caching requirements and data structures.