LRU (Least Recently Used)


#include <iostream>
#include <ctime>
#include <windows.h>
#include <climits>
using namespace std;

struct LRUELEM
{
    int data;
    time_t time;
};

#define FREEUP(p) if(p) {delete []p; p = NULL;}

static int getsmalltime(LRUELEM *e, int n);
static int getsameLRU(LRUELEM *e, int data);

int main()
{
    //LRUELEM *e = (LRUELEM*)malloc(3*sizeof(LRUELEM));
   
    int a[5] = {1, 2, 3, 4, 5};
   
    LRUELEM *e = new LRUELEM[3];
   
    for(int i=0; i<3; i++)
    {
        e[i].data = a[i];
        e[i].time = time(NULL);
        Sleep(1000);
    }
   
    for(i=2; i<5; i++)
    {
        if (getsameLRU(e, a[i]) == -1)
        {
            int pos = getsmalltime(e, 3);
            e[pos].data = a[i];
            e[pos].time = time(NULL);
            Sleep(1000);
        } else {
            e[getsameLRU(e, a[i])].time = time(NULL);
            Sleep(1000);
        }
        for(int i=0; i<3; i++)
        {
            cout << e[i].data << "   "<< e[i].time << endl;
        }
        cout << endl;
    }
   
    FREEUP(e);
   
    return 0;
}

static int getsmalltime(LRUELEM *e, int n)
{
    int smalltime = INT_MAX;
    int pos = -1;
    for(int i=0; i<n; i++)
    {
        if(e[i].time<smalltime)
        {
            smalltime = e[i].time;
            pos = i;
        }
    }
    return pos;
}

static int getsameLRU(LRUELEM *e, int data)
{
    for(int i=0; i<3; i++)
    {
        if(e[i].data == data)
        {
            return i;
        }
    }
    return -1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值