Skip to content

Commit b968d86

Browse files
authored
Fix: Implement LRUCache and resolve build error
1 parent 3826ca1 commit b968d86

File tree

1 file changed

+38
-28
lines changed

1 file changed

+38
-28
lines changed

src/LFUCache.cpp

Lines changed: 38 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,57 @@
1-
#include "LFUCache.h"
2-
#include <iostream>
1+
#include "LRUCache.h"
2+
#include <algorithm> // Required for std::find
33

4-
LFUCache::LFUCache(int capacity) : capacity(capacity) {}
4+
LRUCache::LRUCache(int capacity) : capacity(capacity) {}
55

6-
int LFUCache::get(int key) {
6+
// Private helper to move a key to the front of the access_order list
7+
void LRUCache::moveToFront(int key) {
8+
access_order.remove(key);
9+
access_order.push_front(key);
10+
}
11+
12+
// Private helper to evict the least recently used item
13+
void LRUCache::evict() {
14+
if (access_order.empty()) return;
15+
16+
// Get the least recently used key from the back of the list
17+
int key_to_evict = access_order.back();
18+
access_order.pop_back();
19+
20+
// Erase it from the cache map
21+
cache.erase(key_to_evict);
22+
}
23+
24+
int LRUCache::get(int key) {
725
std::lock_guard<std::mutex> lock(cache_mutex);
8-
if (cache.find(key) == cache.end()) return -1;
926

10-
touch(key);
27+
// If key is not in the cache, return -1
28+
if (cache.find(key) == cache.end()) {
29+
return -1;
30+
}
31+
32+
// Key exists, so it's being used. Move it to the front.
33+
moveToFront(key);
34+
35+
// Note: Assuming the value is stored in the 'first' element of the pair
1136
return cache[key].first;
1237
}
1338

14-
void LFUCache::put(int key, int value) {
39+
void LRUCache::put(int key, int value) {
1540
std::lock_guard<std::mutex> lock(cache_mutex);
1641

1742
if (capacity == 0) return;
1843

44+
// If key already exists, update its value and move it to the front
1945
if (cache.find(key) != cache.end()) {
2046
cache[key].first = value;
21-
touch(key);
47+
moveToFront(key);
2248
} else {
49+
// If the cache is full, evict the least recently used item first
2350
if (cache.size() >= capacity) {
2451
evict();
2552
}
26-
cache[key] = {value, 1};
27-
freq_map[1].push_front(key);
28-
}
29-
}
30-
31-
void LFUCache::touch(int key) {
32-
int old_freq = cache[key].second;
33-
cache[key].second++;
34-
freq_map[old_freq].remove(key);
35-
freq_map[cache[key].second].push_front(key);
36-
}
37-
38-
void LFUCache::evict() {
39-
for (auto& item : freq_map) {
40-
if (!item.second.empty()) {
41-
int key_to_evict = item.second.back();
42-
item.second.pop_back();
43-
cache.erase(key_to_evict);
44-
break;
45-
}
53+
// Add the new key-value pair
54+
cache[key] = {value, 0}; // Storing value in .first, .second is unused per your header
55+
access_order.push_front(key);
4656
}
4757
}

0 commit comments

Comments
 (0)