Template Class LRUCache

Class Documentation

template<typename Key, typename Value, template<typename...> class Map = std::unordered_map>
class LRUCache

A template class for LRU (Least Recently Used) Cache.

This class implements a simple LRU cache using a combination of a list and a hash map.

Template Parameters:
  • Key – The type of keys.

  • Value – The type of values.

  • Map – The type of underlying map, defaulted to std::unordered_map.

Public Functions

inline explicit LRUCache(size_t size)

Construct a new LRUCache object.

Parameters:

size – The capacity of the cache.

inline size_t capacity() const

Get the capacity of the cache.

Returns:

The capacity of the cache.

inline void put(const Key &key, const Value &value)

Insert a key-value pair into the cache.

If the key already exists, its value is updated and it is moved to the front. If the cache exceeds its capacity, the least recently used element is removed.

Parameters:
  • key – The key to insert.

  • value – The value to insert.

inline std::optional<Value> get(const Key &key)

Retrieve a value from the cache.

If the key does not exist in the cache, std::nullopt is returned. If the key exists, the value is returned and the element is moved to the front.

Parameters:

key – The key to retrieve.

Returns:

The value associated with the key, or std::nullopt if the key does not exist.

inline void clear()

Clear the cache.

This removes all elements from the cache.

inline size_t size() const

Get the current size of the cache.

Returns:

The number of elements in the cache.

inline bool empty() const

Check if the cache is empty.

Returns:

True if the cache is empty, false otherwise.

inline bool contains(const Key &key) const

Check if a key exists in the cache.

Parameters:

key – The key to check.

Returns:

True if the key exists, false otherwise.