Skip to content

Class loon::LRU

template <typename K, typename V>

ClassList > loon > LRU

A Least Recently Used ( LRU ) cache with O(1) access and eviction.More...

  • #include <lru.hpp>

Public Functions

Type Name
LRU (uint32_t size)
Constructs an LRU cache with the specified capacity.
bool exists (const K & key) const
Checks if a key exists in the cache.
std::optional< std::reference_wrapper< V > > get (const K & key)
Retrieves a value from the cache.
void put (const K & key, const V & value)
Inserts or updates a key-value pair in the cache.
void remove (const K & key)
Removes a key-value pair from the cache.
uint32_t size () const
Returns the current number of entries in the cache.

Detailed Description

This cache maintains a fixed capacity and automatically evicts the least recently used entries when the capacity is exceeded. Both get() and put() operations update the recency of the accessed key.

Template parameters:

  • K Key type (must be hashable for std::unordered_map)
  • V Value type
loon::LRU<std::string, int> cache(100);
cache.put("key", 42);
if (auto val = cache.get("key")) {
    std::cout << val->get() << std::endl;
}

Public Functions Documentation

function LRU

Constructs an LRU cache with the specified capacity.

inline explicit loon::LRU::LRU (
    uint32_t size
) 

Parameters:

  • size Maximum number of entries the cache can hold.

function exists

Checks if a key exists in the cache.

inline bool loon::LRU::exists (
    const K & key
) const

This operation does not affect the recency of the key.

Parameters:

  • key The key to check.

Returns:

true if the key exists, false otherwise.


function get

Retrieves a value from the cache.

inline std::optional< std::reference_wrapper< V > > loon::LRU::get (
    const K & key
) 

If the key exists, it is marked as most recently used.

Parameters:

  • key The key to look up.

Returns:

A reference to the value if found, std::nullopt otherwise.


function put

Inserts or updates a key-value pair in the cache.

inline void loon::LRU::put (
    const K & key,
    const V & value
) 

If the key already exists, its value is updated and it becomes the most recently used. If the cache is at capacity, the least recently used entry is evicted before inserting the new entry.

Parameters:

  • key The key to insert or update.
  • value The value to associate with the key.

function remove

Removes a key-value pair from the cache.

inline void loon::LRU::remove (
    const K & key
) 

If the key does not exist, this operation has no effect.

Parameters:

  • key The key to remove.

function size

Returns the current number of entries in the cache.

inline uint32_t loon::LRU::size () const

Returns:

The number of cached entries.



The documentation for this class was generated from the following file include/loon/lru.hpp