#pragma once
#include <list>
#include <unordered_map>
template<typename K, typename V>
class LRUCache
{
public:
LRUCache(size_t _capcity):capcity(_capcity)
{
}
~LRUCache()
{
}
void put(K key ,V value)
{
if (dic.count(key))
{
auto it = dic[key];
*it = { key, value };
data.splice(data.begin(), data, it);
}
else
{
data.push_front({ key, value });
dic[key] = data.begin();
}
while (data.size() > capcity)
{
dic.erase(data.back().first);
data.pop_back();
}
}
V get(K key)
{
if (!dic.count(key)) return -1;
auto it = dic[key];
data.splice(data.begin(), data, it);
return it->second;
}
private:
size_t capcity;
std::list<std::pair<K, V>> data;
std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> dic;
};
This class has a constructor with initial list.
#pragma once
#include "LRUCache.h"
class SLRU
{
public:
SLRU();
~SLRU();
private:
LRUCache<std::string, int> protectLRU{ 10 };
LRUCache<std::string, int> eliminateLRU{ 10 };
};
SLRU::SLRU()
{
}
SLRU::~SLRU()
{
}
this class wants to initialize a LRUCache member.
i find that if the LRUCache's constructor has no initial list
LRUCache(size_t _capcity)
{
capcity = _capcity;
}
i can use '()' to initialize the LRUCache member
LRUCache<std::string, int> eliminateLRU(10);
otherwise, i can not use '()'. so what magic does '{}‘ has betwen it and initial list? where can i find the answer when meeting the problem like it?
Aucun commentaire:
Enregistrer un commentaire