借助C++实现LRU页面置换算法

什么是LRU页面置换算法

LRU(Least Recently Used),是页面置换算法的一种,它的主要思想是当用于缓存页面的地址块已满时,选择最久未使用的页面删除,然后用将新请求的页面加入缓存。

例如:请求为 {1, 2, 0, 3, 0, 1, 2, 3, 2},缓存大小为3,那么

 120301232
地址块1111333222
地址块2-22221111
地址块2--0000033

 

实现代码

使用双向链表,每次删除时删除链表第一个页面,加入页面时放在链表末尾。

如果发现请求的页面已经在链表中了,那么直接把这个页面移动到链表末尾。

查找页面是否在链表中可以使用unordered_map实现。

//LRU
#include <iostream>
#include <vector>
#include <cstdio>
#include <unordered_map>
using namespace std;

#define MAX_LEN 4

struct Node {
    int val;
    Node *next, *last;
    Node(int v) : val(v) {}
};

unordered_map<int, Node*> in_list;
Node* head;
Node* tail;
int list_len = 0;

void pushBack(Node *newNode) {
    newNode->next = tail;
    newNode->last = tail->last;
    newNode->last->next = newNode;
    tail->last = newNode;
    in_list[newNode->val] = newNode;
    list_len++;
    printf("%d : in!\n", newNode->val);
}

void popFront() {
    if (head->next == tail) return;
    Node* first = head->next;
    head->next = first->next;
    first->next->last = head;

    in_list[first->val] = nullptr;
    list_len--;
    printf("%d : out!\n", first->val);
    delete first;
}

void print() {
    Node* tmp = head->next;
    while(tmp != tail) {
        printf("%d ", tmp->val);
        tmp = tmp->next;
    }
    printf("\n");

//    tmp = tail->last;
//    while(tmp != head) {
//        printf("%d ", tmp->val);
//        tmp = tmp->last;
//    }
//    printf("\n");
}

int main() {
    // upcoming pages
    vector<int> v = {1, 2, 0, 3, 0, 1, 2, 3, 2};

    head = new Node(0);
    tail = new Node(0);
    head->next = tail, tail->last = head;

    for (int id : v) {
        if (in_list[id] != NULL && in_list[id] != nullptr) {
            Node* p = in_list[id];
            p->last->next = p->next;
            p->next->last = p->last;
            delete p;
            list_len--;
        }
        if (list_len >= MAX_LEN) popFront();
        Node* newNode = new Node(id);
        pushBack(newNode);
        print();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值