赞
踩
LFU的每个数据块都有一个引用计数,所有数据块按照引用计数排序,具有相同引用计数的数据块则按照时间排序。
具体实现如下:
1. 新加入数据插入到队列尾部(因为引用计数为1);
2. 队列中的数据被访问后,引用计数增加,队列重新排序;
3. 当需要淘汰数据时,将已经排序的列表最后的数据块删除。
- /*************************************************************************
- > File Name: Lfu.cpp
- > Author:zhangtx
- > Mail: zhangtx@jinher.com
- > Created Time: 2018年03月30日 星期五 15时50分24秒
- ************************************************************************/
- #include <map>
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/time.h>
- using namespace std;
- class LFUCache {
- public:
- /*
- * @param capacity: An integer
- */LFUCache(int capacity) {
- // do intialization if necessary
- m_capacity=capacity;
- m_count = 0;
- }
-
- void remove_least_used_key()
- {
- map<int,int>::iterator iterBegin=m_countMap.begin();
- map<int,int>::iterator pos =iterBegin;
- for(;iterBegin!=m_countMap.end();iterBegin++)
- {
- if (pos->second>iterBegin->second)
- {
- pos=iterBegin;
- }
- else if (pos->second==iterBegin->second)
- {
- if (m_keytotime[pos->first]>m_keytotime[iterBegin->first])
- {
- pos=iterBegin;
- }
- }
- }
- cout<<endl<<"remove "<<pos->first<<endl;
- m_dataMap.erase(m_dataMap.find(pos->first));
- m_keytotime.erase(m_keytotime.find(pos->first));
- m_countMap.erase(pos);
- m_count--;
-
- }
-
- /*
- * @param key: An integer
- * @param value: An integer
- * @return: nothing
- */
- void set(int key, int value) {
- // write your code here
- if (m_countMap.find(key) != m_countMap.end())
- {
- m_countMap[key]=m_countMap[key]+1;
- m_dataMap[key]=value;
- }
- else
- {
- if ((m_count>=m_capacity))
- {
- remove_least_used_key();
- }
- m_countMap[key]=1;
- m_dataMap[key]=value;
- m_count++;
- }
- struct timezone tz;
- struct timeval tv;
- gettimeofday (&tv , &tz);
- m_keytotime[key]=tv.tv_sec*1000000+tv.tv_usec;
- }
-
- /*
- * @param key: An integer
- * @return: An integer
- */
- int get(int key) {
- // write your code here
- if (m_dataMap.find(key)!=m_dataMap.end())
- {
- struct timezone tz;
- struct timeval tv;
- gettimeofday (&tv , &tz);
- m_keytotime[key]=tv.tv_sec*1000000+tv.tv_usec;
-
- m_countMap[key]=m_countMap[key]+1;
- return m_dataMap[key];
- }
- else
- return -1;
- }
- private:
- int m_capacity;
- int m_count;
- map<int,int> m_dataMap;
- map<int,int> m_countMap;
- map<int,long> m_keytotime;
-
- };
- int main(int argc,char *argv[])
- {
- cout<<endl;
- cout<<endl;
- LFUCache *lfu=new LFUCache(3);
- lfu->set(1,10);
- lfu->set(2,20);
- lfu->set(3,30);
- cout<<lfu->get(1)<<" ";
- lfu->set(4, 40);
- cout<<lfu->get(4)<<" ";
- cout<<lfu->get(3)<<" ";
- cout<<lfu->get(2)<<" ";
- cout<<lfu->get(1)<<" ";
- lfu->set(5, 50);
- cout<<lfu->get(1)<<" ";
- cout<<lfu->get(2)<<" ";
- cout<<lfu->get(3)<<" ";
- cout<<lfu->get(4)<<" ";
- cout<<lfu->get(5)<<" ";
- delete lfu;
-
- cout<<endl;
- cout<<endl;
- cout<<endl;
- }
lfu
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。