-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
54 lines (43 loc) · 1.09 KB
/
LRUCache.cpp
File metadata and controls
54 lines (43 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "LRUCache.h"
#include <stdexcept>
#include <iostream>
LRUCache::LRUCache(size_t capacity) : cap_(capacity) {
if (cap_ == 0) {
throw std::invalid_argument("Capacity must be greater than 0");
}
}
int LRUCache::get(int key) {
auto it = map_.find(key);
if (it == map_.end()) {
return -1;
}
touch(it->second);
return it->second->second;
}
void LRUCache::print() const {
std::cout << "Cache (MRU -> LRU): ";
for (const auto& [k, v] : dll_) {
std::cout << "[" << k << ":" << v << "] ";
}
std::cout << "\n";
}
void LRUCache::put(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
it->second->second = value;
touch(it->second);
return;
}
dll_.push_front({key, value});
map_[key] = dll_.begin();
evictIfNeeded();
}
void LRUCache::touch(std::list<std::pair<int,int>>::iterator it) {
dll_.splice(dll_.begin(), dll_, it);
}
void LRUCache::evictIfNeeded() {
if (dll_.size() <= cap_) return;
auto lru = dll_.back();
map_.erase(lru.first);
dll_.pop_back();
}