Skip to content

Instantly share code, notes, and snippets.

@Red-Eyed
Last active November 2, 2023 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Red-Eyed/bda27ab27acbc5ed5cd6612ee3074d36 to your computer and use it in GitHub Desktop.
Save Red-Eyed/bda27ab27acbc5ed5cd6612ee3074d36 to your computer and use it in GitHub Desktop.
C++ lru cache like in python
#include <iostream>
#include <functional>
#include <unordered_map>
#include <tuple>
// Define a hash function for std::tuple so that it can be used as a key in std::unordered_map
namespace std {
template <typename... T>
struct hash<std::tuple<T...>> {
size_t operator()(const std::tuple<T...>& t) const {
return std::hash<std::tuple<T...>>{}(t);
}
};
}
template <typename... Args, typename ReturnType>
std::function<ReturnType(Args...)> lru_cache(size_t max_size, std::function<ReturnType(Args...)> func) {
std::unordered_map<std::tuple<Args...>, ReturnType> cache;
std::list<std::tuple<Args...>> order;
return [=](Args... args) mutable -> ReturnType {
const auto key = std::make_tuple(args...);
const auto cached = cache.find(key);
if (cached != cache.end()) {
// Move the accessed item to the front (most recently used)
order.remove(key);
order.push_front(key);
return cached->second;
} else {
const auto result = func(args...);
if (cache.size() >= max_size) {
const auto& last_key = order.back();
cache.erase(last_key);
order.pop_back();
}
cache[key] = result;
order.push_front(key);
return result;
}
};
}
// Example usage:
int expensive_function(int a, int b) {
std::cout << "Computing result for " << a << ", " << b << std::endl;
return a + b;
}
int main() {
auto cached_function = lru_cache(2, expensive_function);
std::cout << cached_function(1, 2) << std::endl; // Computes and caches
std::cout << cached_function(1, 2) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment