#include <iostream>
#include <unordered_map>
#include <list>
template <typename K, typename V>
class hashLRU
{
private:
std::unordered_map<K,typename std::list<std::pair<K, V>>::iterator> mp;
std::list<std::pair<K, V>> ls;
int size;
public:
hashLRU(const int& size = 4) : size(size) {}
~hashLRU()
{
}
void put(K key, V value);
V get(K key);
};
template <typename K, typename V>
void hashLRU<K, V>::put(K key, V value)
{
auto it = mp.find(key);
if (it != mp.end())
{
ls.erase(mp[key]);
}
ls.emplace_front(key, value);
mp[key] = ls.begin();
if (this->size < ls.size())
{
K k = ls.back().first;
mp.erase(k);
ls.pop_back();
}
}
template <typename K, typename V>
V hashLRU<K, V>::get(K key)
{
auto it = mp.find(key);
if (it != mp.end())
{
ls.emplace_front(std::make_pair(mp[key]->first, mp[key]->second));
ls.erase(mp[key]);
mp[key] = ls.begin();
return mp[key]->second;
}
return V();
}
int main(int argc, char** argv)
{
hashLRU<int,std::string> hash(5);
std::cout << hash.get(3) << std::endl;
hash.put(3,"你好");
hash.put(2, "hello");
hash.put(6, "aaa");
hash.put(8, "bbb");
hash.put(1, "ddd");
hash.put(6, "adg");
hash.put(7, "dddsa");
hash.put(10, "ghh");
std::cout << hash.get(2) << std::endl;
std::cout << hash.get(1) << std::endl;
std::cout << hash.get(8) << std::endl;
return 0;
}