LRU算法 c++实现

LRU全程Least Recently Used,最近最少使用的意思,是一种内存管理方法,该算法最早应用于操作系统。

#include<list>
#include<string>
#include<unordered_map>
using namespace std;

template<class KeyType, class ValueType>
class LRUCache
{
public:
	LRUCache(int capacity) : m_capacity(capacity) {}

	int get(KeyType key, ValueType &value)
	{
		if (m_map.count(key) <= 0)
		{
			return -1;
		}

		Iter iter = m_map[key];
		value = iter->second;

		m_list.splice(m_list.begin(), m_list, iter);

		return 0;
	}

	void put(KeyType key, ValueType value)
	{
		if (m_map.count(key) >= 1)
		{
			Iter iter = m_map[key];
			iter->second = value;
			m_list.splice(m_list.begin(), m_list, iter);
		}
		else
		{
			Node node(key, value);
			if (m_list.size() == m_capacity)
			{
				m_map.erase(m_list.back().first);
				m_list.pop_back();
			}

			m_list.push_front(node);
			m_map[key] = m_list.begin();
		}
	}

	void show(void(*p)(ValueType *))
	{
		typename  list<Node>::iterator it;
		for (it = m_list.begin(); it != m_list.end(); it++)
		{
			p(&it->second);
		}
	}

private:
	typedef  pair<KeyType, ValueType> Node;
	typedef typename  list<Node>::iterator Iter;
	list<Node> m_list;
	unordered_map<KeyType, Iter> m_map;
	int m_capacity;
};


void show_func(int *a)
{
	printf("%d\n", *a);
}

int main()
{
	int value;
	LRUCache< string, int> cache(5);
	cache.put("aaa", 1);
	cache.put("bbb", 2);
	cache.put("ccc", 3);
	cache.put("ddd", 4);
	cache.put("eee", 5);

	cache.show(show_func);

	cache.get("ccc", value);

	cache.show(show_func);

	cache.put("fff", 6);

	cache.show(show_func);

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值