35 lines
793 B
C++
35 lines
793 B
C++
#pragma once
|
|
#include <functional>
|
|
#include <map>
|
|
|
|
|
|
namespace drp::util {
|
|
|
|
|
|
template<class Key, class Value, int limit, class Comparator = std::less<Value>>
|
|
class CacheMap : std::map<Key, Value> {
|
|
public:
|
|
void cache() {
|
|
// check if the limit have been reached.
|
|
if (this->size() <= limit)
|
|
return;
|
|
|
|
// apply the comparator on all the value to find the minimum.
|
|
auto minimum = this->begin();
|
|
for (const auto& it : this)
|
|
if (Comparator()(it.second, minimum))
|
|
minimum = it;
|
|
|
|
// delete this lowest value.
|
|
this->erase(minimum);
|
|
}
|
|
|
|
Value& operator[](const Key& key) {
|
|
const auto& value = std::map<Key, Value>::operator[](key);
|
|
this->cache();
|
|
return value;
|
|
}
|
|
};
|
|
|
|
|
|
}
|