1 )基本原理lfu(leastfrequentlyused )算法基于过去对数据的访问频率丢弃数据,其核心思想是“如果数据过去被多次访问,将来被访问的频率也会变高”。 LFU中的每个数据块都有引用计数,所有数据块按引用计数排序,具有相同引用计数的数据块按时间排序。

具体情况如下。

1 .在队列末尾插入新添加的数据(因为引用数为1 );

2 .队列中的数据被访问后,引用计数增加,队列被重新排序

3 .如果需要丢弃数据,请删除已排序列表中的最后一个数据块。

2、代码/* * * * * * * * * * * * * * * * * * *代码/* * * * * * * * * * * * * * filename : lfu.CPP author : zhangt xmail : zhangtx @ jinher.comcreatedtime 33602018年03月30日星期五15时50分24秒* * * * * * * * * * * * include stdio classlfucache { public :/* * @ param capacity : an integer */lfucache (int capacity )/dointializationionifnefned } void remove_least_used_key () { mapint,int :3360 iteratoriterbegin=m _ count map.begin ); mapint,int :3360 iterator pos=ITER begin; for (; iterBegin!=m_countMap.end (; iterbegin(if ) pos-seconditerbegin-second { pos=ITER begin; } else if (pos-second==ITER begin-second ) if ) m _ key to time [ pos-first ] m _ key to time [ ITER begin-first ] ) } } cout endl ‘ remove ‘ pos-first endl; m_datamap.erase(m_datamap.find ) pos-first ); m _ key to time.erase (m _ key to time.find ) pos-first ); m_countmap.erase(pos; m_count–; }/* * @ param key : an integer * @ param value : an integer * @ return : nothing */voidset (intkey,int value ) )/woid 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; gttimeofday(TV,tz ); m _ key to time [ key ]=TV.TV _ sec * 1000000 TV.TV _ usec; }/* * @ param key : an integer * @ return : an integer */int get (intkey )//writeyourcodehereif (m _ data map.fin nin struct timeval tv; gttimeofday(TV,tz ); m _ key to time [ key ]=TV.TV _ sec * 1000000 TV.TV _ usec; m _ count map [ key ]=m _ count map [ key ] 1; return m_dataMap[key]; } else return -1; }private: int m_capacity; int m_count; 映射int,int m_dataMap; 映射int,int m_countMap; mapint,long m_keytotime; (; intmain(intargc,char *argv[] ) {coutendl; coutendl; lfucache*lfu=newlfucache(3; lfu-set (1,10 ); lfu-set (2,20; lfu-set (3,30; coutlfu-get(1) ‘; lfu-set (4,40; coutlfu-get(4) ‘; coutlfu-get(3) ‘; coutlfu-get(2) ‘; coutlfu-get(1) ‘; lfu-set (5,50; coutlfu-get(1) ‘; coutlfu-get(2) ‘; coutlfu-get(3) ‘; coutlfu-get(4) ‘; coutlfu-get(5) ); 删除lfu; coutendl; coutendl; coutendl; () ) ) ) )。

lfu