Skip to content

Instantly share code, notes, and snippets.

@meehatpa
Created August 17, 2020 05:48
Show Gist options
  • Save meehatpa/b31e19eb02c5aed303f6cd2e4b60fec5 to your computer and use it in GitHub Desktop.
Save meehatpa/b31e19eb02c5aed303f6cd2e4b60fec5 to your computer and use it in GitHub Desktop.
LRU cache cpp implementation
#include <iostream>
#include <list>
#include <map>
class cache {
public:
cache(int s) : size(s) {};
void put(int k) {
if (addressMap.find(k) != addressMap.end()) return;
contents.push_back(k);
addressMap[k] = --contents.end();
if (contents.size() > size) {
addressMap.erase(contents.front());
contents.pop_front();
}
}
void get(int k) {
printf("val %d : ", k);
auto kIter = addressMap.find(k);
if (kIter != addressMap.end()) {
printf("Cache hit\n");
contents.erase(addressMap[k]);
addressMap.erase(k);
} else {
printf("missed\n");
}
put(k);
}
void printContents() {
printf("contents order: ");
for (const auto &c : contents)
printf("%d,", c);
printf("\ncontents map: ");
for (const auto &a : addressMap)
printf("%d,", a.first);
printf("\n");
}
private:
std::list<int> contents;
int size;
std::map<int, std::list<int>::iterator> addressMap;
};
int main() {
cache C(2);
C.put(1);
C.put(2);
C.put(3);
C.put(10);
C.printContents();
C.get(3); C.printContents();
C.get(30); C.printContents();
C.get(20); C.printContents();
C.put(3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment