LRU -> list + hash_map
LRU算法及缓存淘汰的思想,常用的数据仍为常用的热点数据,保存队列中
不常用的数据认为冷数据,从缓存队列移除,每次新创建数据或者更新数据
扔到数据队列头部,采用双链表+hash表结构设计,降低时间复杂度。
struct node {
int m_hash_map_key;
int m_hash_map_val;
node * m_pre;
node * m_next;
public:
node(int pkey, int pval) {
m_hash_map_key = pkey;
m_hash_map_val = pval;
m_pre = NULL;
m_next = NULL;
}
};
class CLRUALG {
public:
CLRUALG();
~CLRUALG();
public:
void set(node * pnode);
int get(node * pnode);
private:
//移除
void remove(node * pnode);
//放到头队列
void set_head(node * pnode);
private:
std::unordered_map<int, node*> m_hash_map;
int m_lru_capacity;
node* m_phead;
node* m_ptail;
};
CLRUALG::CLRUALG() {
}
CLRUALG::~CLRUALG() {
}
void CLRUALG::remove(node * pnode) {
if (pnode->m_pre != NULL) {
pnode->m_pre->m_next = pnode->m_next;
} else {
m_phead = pnode->m_next;
}
if (pnode->m_next != NULL) {
pnode->m_next->m_pre = pnode->m_pre;
} else {
m_ptail = pnode->m_pre;
}
}
void CLRUALG::set_head(node * pnode) {
pnode->m_next = m_phead;
pnode->m_pre = NULL;
if (m_phead != NULL) {
m_phead->m_pre = pnode;
}
m_phead = pnode;
if (m_ptail == NULL)
{
m_ptail = m_phead;
}
}
int CLRUALG::get(node * pnode) {
auto iter = m_hash_map.find(pnode->m_hash_map_key);
if (iter != m_hash_map.end()) {
auto val = iter->second;
remove(pnode);
set_head(pnode);
return val->m_hash_map_val;
} else {
return -1;
}
}
void CLRUALG::set(node * pnode) {
auto iter = m_hash_map.find(pnode->m_hash_map_key);
if (iter != m_hash_map.end())
{
node * lnode = iter->second;
lnode->m_hash_map_val = pnode->m_hash_map_val;
remove(lnode);
set_head(lnode);
}
if (m_hash_map.size() >= m_lru_capacity)
{
auto ptail = m_hash_map.find(m_ptail->m_hash_map_key);
remove(ptail->second);
m_hash_map.erase(ptail);
}
m_hash_map[pnode->m_hash_map_key] = pnode;
set_head(pnode);
}