Template'ing Key parameter
This commit is contained in:
parent
ecb979a14b
commit
41b381f567
@ -24,28 +24,28 @@ or see http://www.gnu.org/licenses/agpl.txt.
|
|||||||
#include <list>
|
#include <list>
|
||||||
#include <boost/unordered_map.hpp>
|
#include <boost/unordered_map.hpp>
|
||||||
|
|
||||||
template<typename ValueT>
|
template<typename KeyT, typename ValueT>
|
||||||
class LRUCache {
|
class LRUCache {
|
||||||
private:
|
private:
|
||||||
struct CacheEntry {
|
struct CacheEntry {
|
||||||
CacheEntry(unsigned k, ValueT v) : key(k), value(v) {}
|
CacheEntry(KeyT k, ValueT v) : key(k), value(v) {}
|
||||||
unsigned key;
|
KeyT key;
|
||||||
ValueT value;
|
ValueT value;
|
||||||
};
|
};
|
||||||
unsigned capacity;
|
unsigned capacity;
|
||||||
std::list<CacheEntry> itemsInCache;
|
std::list<CacheEntry> itemsInCache;
|
||||||
boost::unordered_map<unsigned, typename std::list<CacheEntry>::iterator > positionMap;
|
boost::unordered_map<KeyT, typename std::list<CacheEntry>::iterator > positionMap;
|
||||||
public:
|
public:
|
||||||
LRUCache(unsigned c) : capacity(c) {}
|
LRUCache(unsigned c) : capacity(c) {}
|
||||||
|
|
||||||
bool Holds(unsigned key) {
|
bool Holds(KeyT key) {
|
||||||
if(positionMap.find(key) != positionMap.end()) {
|
if(positionMap.find(key) != positionMap.end()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Insert(const unsigned key, ValueT value) {
|
void Insert(const KeyT key, ValueT &value) {
|
||||||
itemsInCache.push_front(CacheEntry(key, value));
|
itemsInCache.push_front(CacheEntry(key, value));
|
||||||
positionMap.insert(std::make_pair(key, itemsInCache.begin()));
|
positionMap.insert(std::make_pair(key, itemsInCache.begin()));
|
||||||
if(itemsInCache.size() > capacity) {
|
if(itemsInCache.size() > capacity) {
|
||||||
@ -53,7 +53,7 @@ public:
|
|||||||
itemsInCache.pop_back();
|
itemsInCache.pop_back();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
bool Fetch(const unsigned key, ValueT& result) {
|
bool Fetch(const KeyT key, ValueT& result) {
|
||||||
if(Holds(key)) {
|
if(Holds(key)) {
|
||||||
CacheEntry e = *(positionMap.find(key)->second);
|
CacheEntry e = *(positionMap.find(key)->second);
|
||||||
result = e.value;
|
result = e.value;
|
||||||
|
Loading…
Reference in New Issue
Block a user