Back to code C++

Una caché que olvida lo que hace más tiempo no se usa

Caché LRU con una lista y un mapa: buscar, guardar y desalojar en tiempo constante.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

Consultar el mismo dato caro una y otra vez es desperdicio, pero guardar todo para siempre agota la memoria. Hace falta una caché con tope que descarte lo menos usado.

C++
#include <iostream>
#include <list>
#include <string>
#include <unordered_map>

class CacheLRU {
    size_t capacidad;
    std::list<std::pair<std::string, std::string>> orden;   // el frente es lo más reciente
    std::unordered_map<std::string, decltype(orden)::iterator> indice;
public:
    explicit CacheLRU(size_t n) : capacidad(n) {}

    const std::string* obtener(const std::string& clave) {
        auto it = indice.find(clave);
        if (it == indice.end()) return nullptr;
        orden.splice(orden.begin(), orden, it->second);       // lo usado pasa al frente
        return &it->second->second;
    }

    void guardar(const std::string& clave, const std::string& valor) {
        if (auto it = indice.find(clave); it != indice.end()) orden.erase(it->second);
        orden.emplace_front(clave, valor);
        indice[clave] = orden.begin();
        if (orden.size() > capacidad) { indice.erase(orden.back().first); orden.pop_back(); }
    }
};

int main() {
    CacheLRU cache(2);
    cache.guardar("a", "1"); cache.guardar("b", "2");
    cache.obtener("a");                 // "a" vuelve a ser reciente
    cache.guardar("c", "3");            // sale "b"
    std::cout << (cache.obtener("b") ? "b sigue" : "b salió") << "\n";
}

Why it is written this way

  1. La lista guarda el orden de uso; el mapa guarda, para cada clave, dónde está en la lista. Juntas dan todo en tiempo constante.
  2. splice mueve un nodo al frente sin copiarlo ni invalidar los iteradores que el mapa tiene guardados.
  3. Cuando se pasa de la capacidad, lo que sale es el último de la lista: lo que hace más tiempo no se toca.
  4. obtener devuelve un puntero: nullptr significa "no está", sin excepciones ni valores mágicos.
How to try it

Guardalo como lru.cpp y corré: c++ -std=c++17 -Wall -o lru lru.cpp && ./lru

Watch out

No es segura entre hilos: dos hilos a la vez corrompen la lista. Y el puntero que devuelve obtener deja de valer si esa clave se desaloja después.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo esta caché LRU en C++17. Convertila en una plantilla genérica para cualquier tipo de clave y valor, hacela segura entre hilos con un mutex, que obtener devuelva std::optional en vez de puntero, y agregá vencimiento por tiempo de [SEGUNDOS] segundos por entrada. La voy a usar para cachear [QUÉ DATOS]. Incluí una prueba mínima en main.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.