您的位置:首页 > 编程语言 > C语言/C++

LRU的C++的简单实现

2014-08-20 22:58 253 查看
class LRUCache提供两个接口:get(int key)和set(int key,value)

#include<iostream>

using namespace std;

class LRUCache{
public:
LRUCache(int cap):current(0),capacity(cap){
A=new node[cap];
}
int get(int key) {
for(int i=0;i<current;i++)
{
if(key==A[i].key)
{
int temp=A[i].value;
node tt=A[i];
for(int k=i;k<current-1;k++)
{
A[k]=A[k+1];
}
A[current-1]=tt;
return temp;
}
}
return -1;
}
void set(int key, int value) {
node t;
t.key=key;
t.value=value;
bool has=false;
for(int i=0;i<current;i++)
{
if(key==A[i].key)
{
A[i].value=value;
node tt=A[i];
for(int k=i;k<current-1;k++)
{
A[k]=A[k+1];
}
A[current-1]=tt;
has=true;
break;
}
}
if(!has)
{

if(current<capacity)
{
A[current++]=t;
}else{
for(int k=0;k<current-1;k++)
{
A[k]=A[k+1];
}
A[current-1]=t;
}
}
print();
}
void print()
{
for(int i=0;i<current;i++)
cout<<A[i].key<<" ";
cout<<endl;
}
private:
int current;
int capacity;
struct node{
int key;
int value;
};
void swap(node &a,node &b)
{
node temp;
temp=a;
a=b;
b=temp;
}
node *A;
};
int main()
{
LRUCache lru(4);

lru.set(2,1);
lru.set(2,2);
lru.set(3,2);
lru.set(4,2);
lru.set(5,2);
lru.set(1,2);
lru.set(4,2);
lru.set(3,2);
lru.set(4,2);
lru.get(1);
lru.print();

}


测试:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: