Class loon::LRU¶
template <typename K, typename V>
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:
KKey type (must be hashable for std::unordered_map)VValue 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.
Parameters:
sizeMaximum number of entries the cache can hold.
function exists¶
Checks if a key exists in the cache.
This operation does not affect the recency of the key.
Parameters:
keyThe key to check.
Returns:
true if the key exists, false otherwise.
function get¶
Retrieves a value from the cache.
If the key exists, it is marked as most recently used.
Parameters:
keyThe 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.
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:
keyThe key to insert or update.valueThe value to associate with the key.
function remove¶
Removes a key-value pair from the cache.
If the key does not exist, this operation has no effect.
Parameters:
keyThe key to remove.
function size¶
Returns the current number of entries in the cache.
Returns:
The number of cached entries.
The documentation for this class was generated from the following file include/loon/lru.hpp