This is a simple C++ implementation of an LRU (Least Recently Used) cache, which is a data structure used for storing a fixed number of items and evicting the least recently used item when the cache is full.
- Supports
getValue(key)andinsertKeyValue(key, value)operations. - Time complexity of both
getandputoperations is O(1).
- Include the
iostream,unordered_mapandlistfile in your C++ project. - Create an instance of
LRUCacheby specifying the maximum capacity. - Use the
getValue(key)method to retrieve the value associated with a key. - Use the
insertKeyValue(key, value)method to insert or update a key-value pair.
#include "LRUCache.cpp"
int main()
{
LRUCache lru(3);
lru.insertKeyValue("π₯", 10);
lru.insertKeyValue("π", 20);
lru.insertKeyValue("π", 30);
std::cout << "Most Recently Used: " << lru.mostRecentKey() << std::endl;
lru.insertKeyValue("π₯", 40);
std::cout << "Most Recently Used: " << lru.mostRecentKey() << std::endl;
lru.insertKeyValue("π", 20);
if (lru.getValue("π") == NULL)
{
std::cout << "Apple doesn't exists" << std::endl;
}
if (lru.getValue("π₯") == NULL)
{
std::cout << "Mango doesn't exists" << std::endl;
}
if (lru.getValue("π") == NULL)
{
std::cout << "Grages doesn't exists" << std::endl;
}
if (lru.getValue("π") == NULL)
{
std::cout << "Banana doesn't exists" << std::endl;
}
return 0;
}