C++實(shí)現(xiàn)支持泛型的LFU詳解
首先定義LFU存儲(chǔ)數(shù)據(jù)節(jié)點(diǎn)ListNode的結(jié)構(gòu), 此結(jié)構(gòu)支持鍵K和值V的模板,為了在有序元素中實(shí)現(xiàn)比較(嚴(yán)格小于),這里需要重載小于號(hào),如果此數(shù)據(jù)的使用頻次最少,則小于結(jié)果為true,如果頻次相等,輪次早的數(shù)據(jù)最小。
template<typename K, typename V> struct ListNode { K key; V value; int freq; long cur; bool operator<(const ListNode &x) const { if (freq < x.freq) return true; else if (freq == x.freq) return cur < x.cur; else return false; } };
然后我們來(lái)實(shí)現(xiàn)lfu類,我們用unordered_map去存key值對(duì)應(yīng)的ListNode,用set<ListNode<K,V>> freq來(lái)充當(dāng)頻次的存儲(chǔ)容器,使用set的好處是自動(dòng)排序,頻次小的數(shù)據(jù)迭代器會(huì)被排到freq的begin(),刪除是只需要erase掉begin所指向的迭代器即可。我們來(lái)具體分析get和put操作
- get操作首先去map中查詢此key對(duì)應(yīng)ListNode是否存在,如果此數(shù)據(jù)存在,將其對(duì)應(yīng)的頻次+1(這里用reinsert函數(shù)實(shí)現(xiàn)),如果數(shù)據(jù)不存在,返回-1。
- put操作也要去map中查詢此key對(duì)應(yīng)ListNode是否存在,若存在,直接將ListNode的value更新,并且將其對(duì)應(yīng)的頻次+1(同上),否則,在map對(duì)應(yīng)此鍵值的桶中插入ListNode,然后在freq中將其對(duì)應(yīng)的頻次設(shè)為1并插入。
完整代碼如下:
#include <map> #include <set> #include <unordered_map> using namespace std; template<typename K, typename V> struct ListNode { K key; V value; int freq; long cur; bool operator<(const ListNode &x) const { if (freq < x.freq) return true; else if (freq == x.freq) return cur < x.cur; else return false; } }; template<typename K, typename V> class lfu { private: long cur_rount; int capacity; unordered_map<int, ListNode<K, V>> m; set<ListNode<K, V>> freq; public: lfu(int capacity) { capacity = capacity; cur_rount = 0; } V get(K key) { auto it = m.find(key); if (it == m.end()) return -1; V value = it->second.value; reinsert(it->second); return value; } void put(K key, V value) { if (capacity == 0) return; auto it = m.find(key); if (it != m.end()) { it->second.value = value; reinsert(it->second); return; } if (m.size() == capacity) { const ListNode<K, V> &node = *freq.begin(); m.erase(node.key); freq.erase(node); } ListNode<K, V> node{key, value, 1, ++cur_rount}; m[node.key] = node; freq.insert(node); } void reinsert(ListNode<K, V> &node) { freq.erase(node); ++node.freq; node.cur = ++cur_rount; freq.insert(node); } };
這里寫了一個(gè)簡(jiǎn)單的主函數(shù)去驗(yàn)證,K和V都使用int進(jìn)行實(shí)例化。
可以看到第一次查詢,得到key=1的值為8,符合預(yù)期,在插入key=7 value=10的ListNode后,LFU頻次最低的Key=5 ListNode。此時(shí)再去get Key=5的值會(huì)得到一個(gè)-1,符合預(yù)期。
總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
VS2017開發(fā)C語(yǔ)言出現(xiàn)“no_init_all“的解決辦法
這篇文章介紹了VS2017開發(fā)C語(yǔ)言出現(xiàn)“no_init_all“的解決辦法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12C語(yǔ)言實(shí)現(xiàn)猜數(shù)字的小游戲
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)猜數(shù)字的小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-01-01c語(yǔ)言實(shí)現(xiàn)的貨物管理系統(tǒng)實(shí)例代碼(增加刪除 查找貨物信息等功能)
這篇文章主要介紹了c語(yǔ)言實(shí)現(xiàn)的貨物管理系統(tǒng),可增加刪除、查找貨物信息、顯示貨物信息、排序貨物銷量等操作,大家參考使用吧2013-11-11