頁面置換演算法實現
阿新 • • 發佈:2019-02-03
LRU置換演算法(最近最久未使用)
- 利用兩個map,將頁面和位置對應起來。
- 在缺頁的情況下對map中的頁面與對應位置進行調整即可。
#include<iostream>
#include<map>
#include<vector>
#include<string>
using namespace std;
int calc(const vector<int>& vec) {
map<int, int> page_pos; //頁面對應的位置
map<int, int> pos_page; //位置對應的頁面
int len = vec.size();
int time = 1;
for (int i = 0; i < len; ++i) {
if (page_pos.find(vec[i]) == page_pos.end()) {
if (time < 4) {
page_pos[vec[i]] = time;
pos_page[time] = vec[i];
}
else {
page_pos.erase(pos_page[1 ]);
int page_2 = pos_page[2];
int page_3 = pos_page[3];
page_pos[page_2] = 1;
page_pos[page_3] = 2;
pos_page[1] = page_2;
pos_page[2] = page_3;
page_pos[vec[i]] = 3;
pos_page[3 ] = vec[i];
}
cout << "第" << time++ << "次缺頁:" << vec[i] << endl;
}
else {
int page = page_pos.find(vec[i])->first;
int pos = page_pos.find(vec[i])->second;
switch (pos) {
case 1:
{
int page_2 = pos_page[2];
int page_3 = pos_page[3];
page_pos[page_2] = 1;
page_pos[page_3] = 2;
pos_page[1] = page_2;
pos_page[2] = page_3;
page_pos[page] = 3;
pos_page[3] = page;
}
break;
case 2:
{
int page3 = pos_page[3];
page_pos[page3] = 2;
page_pos[page] = 3;
pos_page[2] = page3;
pos_page[3] = page;
}
break;
case 3:
break;
}
}
}
return --time;
}
int main(int argc, char *argv[]) {
int N; //頁面置換總數
cin >> N;
vector<int> vec(N); //頁面序列
int page;
for (int i = 0; i < N; ++i) {
cin >> page;
vec[i] = page;
}
int missPage = calc(vec);
cout << missPage << endl;
getchar();
return 0;
}
- 結果
先進先出置換演算法
- 前三個頁面直接進入佇列和向量,以缺頁標記。
- 之後的頁面與向量中的頁面進行比較,若找到該頁面,則表示不缺頁;若未找到該頁面,說明頁面不在,需要將隊頭的頁面移除,並將向量中存放隊頭的下標改存該頁面,以缺頁標記。
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int calc(const vector<int>& vec) {
queue<int> q; //儲存頁面次序
vector<int> v(3); //儲存頁面
int len = vec.size();
int time = 1;
for (int i = 0; i < len; ++i) {
if (time < 4) {
v[i] = vec[i];
q.push(vec[i]);
cout << "第" << time++ << "次缺頁:" << vec[i] << endl;
}
else {
if (find(v.begin(), v.end(), vec[i]) == v.end()) {
int page = q.front();
q.pop();
q.push(vec[i]);
*find(v.begin(), v.end(), page) = vec[i];
cout << "第" << time++ << "次缺頁:" << vec[i] << endl;
}
}
}
return --time;
}
int main(int argc, char *argv[]) {
int N; //頁面置換總數
cin >> N;
vector<int> vec(N); //頁面序列
int page;
for (int i = 0; i < N; ++i) {
cin >> page;
vec[i] = page;
}
int missPage = calc(vec);
cout << missPage << endl;
getchar();
return 0;
}
- 結果