【C++实现】LFU缓存

 

#include<iostream>
#include<unordered_map>
#include<algorithm>
using namespace std;

//调试用
//void printList(int obj)
//{
//	cout << obj << "\t";
//}
//void printFun(unordered_map<int, list<int>> &obj)
//{
//	for (unordered_map<int, list<int>>::iterator it = obj.begin(); it != obj.end(); it++)
//	{
//		cout << it->first << "\t";
//		for_each(it->second.begin(), it->second.end(), printList);
//		cout << endl;
//	}
//}

class LFUCache
{
public:
	LFUCache(int capacity)
	{
		this->capacity = capacity;
	}

	void set(int key, int value)
	{
		if (mapData.find(key) != mapData.end())
		{
			int tmp = mapData[key].second;
			mapData[key] = make_pair(value, tmp);
		}
		else
		{
			if (mapData.size() < capacity)
			{
				mapData.insert(make_pair(key, make_pair(value, 0)));
			}
			else
			{
				for (unordered_map<int, list<int>>::iterator it = count_sort.begin(); it != count_sort.end(); it++)
				{
					if (!it->second.empty())
					{
						int topNum = it->second.front();
						it->second.pop_front();
						mapData.erase(topNum);
						mapData.insert(make_pair(key, make_pair(value, 0)));
						break;
					}
				}
			}
		}
		update(key);
	}

	int get(int key)
	{
		if (mapData.find(key) == mapData.end())
		{
			return -1;
		}
		update(key);
		return mapData[key].first;
	}

	//统一更新访问次数
	void update(int key)
	{
		list<int> ::iterator it = find(count_sort[mapData[key].second].begin(), count_sort[mapData[key].second].end(), key);
		if (it != count_sort[mapData[key].second].end())
		{
			count_sort[mapData[key].second].erase(it);
		}
		mapData[key].second++;
		count_sort[mapData[key].second].push_back(key);
		//printFun(count_sort);
	}

private:
	unordered_map<int, list<int>> count_sort;//frequency,key of mapData
	int capacity;
	unordered_map<int, pair<int, int>> mapData;//key,value,count
};




int main()
{
	LFUCache cache(3);
	cache.set(2, 2);
	cache.set(1, 1);
	cout << cache.get(2) <<",";
	cout << cache.get(1) << ",";
	cout << cache.get(2) << ",";
	cache.set(3, 3);
	cache.set(4, 4);
	cout << cache.get(3) << ",";
	cout << cache.get(2) << ",";
	cout << cache.get(1) << ",";
	cout << cache.get(4) << endl;


	//LFUCache cache(2);
	//cache.set(1, 1);
	//cache.set(2, 2);
	//cout << cache.get(1) << endl;       // 返回 1
	//cache.set(3, 3);    // 去除 key 2
	//cout << cache.get(2) << endl;       // 返回 -1 (未找到key 2)
	//cout << cache.get(3) << endl;       // 返回 3
	//cache.set(4, 4);    // 去除 key 1
	//cout << cache.get(1) << endl;       // 返回 -1 (未找到 key 1)
	//cout << cache.get(3) << endl;       // 返回 3
	//cout << cache.get(4) << endl;       // 返回 4
	
	system("pause");
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值