首页 / 算法 / Sword LRU算法
Sword LRU算法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Sword LRU算法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2666字,纯文字阅读大概需要4分钟。
内容图文
![Sword LRU算法](/upload/InfoBanner/zyjiaocheng/1103/3b9b099347ac49bca1e6002fb1f258b5.jpg)
/* LRU算法实现 */ #include <iostream> #include <map> #include <list> #include <functional> /* LRU算法 按照英文的直接原义就是Least Recently Used,最近最久未使用法,它是按照一个非常著名的计算机操作系统基础理论得来的:最近使用的页面数据会在未来一段时期内仍然被使用, 已经很久没有使用的页面很有可能在未来较长的一段时间内仍然不会被使用。基于这个思想,会存在一种缓存淘汰机制,每次从内存中找到最久未使用的数据然后置换出来, 从而存入新的数据!它的主要衡量指标是使用的时间,附加指标是使用的次数。在计算机中大量使用了这个机制,它的合理性在于优先筛选热点数据,所谓热点数据, 就是最近最多使用的数据!因为,利用LRU我们可以解决很多实际开发中的问题,并且很符合业务场景。 */class LRUCache { typedef std::function<void(void *)> DestoryCallback; public: //构造函数 LRUCache(size_t capacity, DestoryCallback cb) :_capacity(capacity), _deallocator(cb) { } //析构函数 ~LRUCache() { for (auto it = this->_store.begin(); it != this->_store.end(); ++it) { if (this->_deallocator) { this->_deallocator(it->second); } } } public: //getvoid * get(int key) { std::map<int, std::list<std::pair<int, void *>>::iterator>::iterator itFind = this->_select.find(key); if (itFind == this->_select.end()) { return NULL; } /* 知识补充: void splice ( iterator position, list<T,Allocator>& x, iterator i ); 函数说明:在list间移动元素,将x的元素移动到目的list的指定位置,高效的将他们插入到目的list并从x中删除。 注意:迭代器i不会失效 */this->_store.splice(this->_store.begin(), this->_store, itFind->second); //将刚查询的key移动到队首return itFind->second->second; } //set voidset(int key, void * value) { std::map<int, std::list<std::pair<int, void *>>::iterator>::iterator itFind = this->_select.find(key); if (itFind != this->_select.end()) { //key 存在this->_store.splice(this->_store.begin(), this->_store, itFind->second); //将刚查询的key移动到队首 itFind->second->second = value; //更新valuereturn; } if (this->_capacity < this->_store.size()) { //缓冲区过载,删除队尾元素int delKey = this->_store.back().first; if (this->_deallocator) { this->_deallocator(this->_store.back().second); } this->_store.pop_back(); this->_select.erase(delKey); } this->_store.emplace_front(key, value); this->_select.insert(std::make_pair(key, this->_store.begin())); } private: size_t _capacity; //缓冲区容量 DestoryCallback _deallocator; //析构方法 std::list<std::pair<int, void *> > _store; //存储 std::map<int, std::list<std::pair<int, void *>>::iterator> _select; //查询 }; int test() { LRUCache cache(5, NULL); cache.set(0, NULL); cache.set(1, NULL); cache.set(2, NULL); cache.set(3, NULL); cache.set(4, NULL); cache.set(5, NULL); cache.set(6, NULL); cache.set(0, NULL); cache.get(5); return0; } int main() { test(); printf("--------ok-------\n"); getchar(); return0; }
LRU算法用于所有数据集都已经确定的场景,如果部分数据不在数据集中,不适合使用LRU算法,会导致大量访问数据库
原文:https://www.cnblogs.com/zhanggaofeng/p/12150253.html
内容总结
以上是互联网集市为您收集整理的Sword LRU算法全部内容,希望文章能够帮你解决Sword LRU算法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。