Skip to content

Instantly share code, notes, and snippets.

@itayB
Created September 21, 2016 21:00
Show Gist options
  • Select an option

  • Save itayB/0456d3604022f7eaa41e6c15d46048aa to your computer and use it in GitHub Desktop.

Select an option

Save itayB/0456d3604022f7eaa41e6c15d46048aa to your computer and use it in GitHub Desktop.
Implement LRU cache
#include <iostream>
#include <string>
#include <unordered_map>
#include <list>
using namespace std;
template <class K, class V> class LRU {
private:
/* Members */
unordered_map<K, pair<typename list<K>::iterator, V > > map;
list<K> linkedList;
int size;
/* Private methods. */
// Assume that key k doesn't exist in cache
void add(K k, V v) {
linkedList.push_front(k);
map[k] = pair< list<K>::iterator, V >(linkedList.begin(), v);
}
public:
// constructor
LRU(int size) {
this->size = size;
}
void put(K k, V v) {
// if key k exist - update
if (map.count(k) > 0) {
linkedList.erase(map[k].first);
}
else if (map.size() == size) { // max size, need to remove least recently used
K last = linkedList.back();
linkedList.pop_back();
map.erase(last);
}
add(k,v);
}
V get(K k) {
if (map.count(k) == 0) {
return nullptr;
}
linkedList.erase(map[k].first);
linkedList.push_front(k);
map[k].first = linkedList.begin();
return map[k].second;
}
void print() {
cout << "Map: ";
for ( auto& p: map ) {
cout << p.first << ",";
}
cout << "\nList: ";
for ( auto& l: linkedList ) {
cout << l << ",";
}
cout << endl;
}
};
int main() {
LRU<int, string> lru(5);
lru.put(1,"A");
lru.put(2,"B");
lru.put(3,"C");
lru.put(4,"D");
lru.put(5,"E");
lru.put(2,"F");
lru.put(6,"G");
lru.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment