FIFO算法是最早出现的置换算法。该算法总是淘汰最先进入内存的页面,即选择在内存中驻留时间最久的页面予以淘汰。该算法实现简单,只需把一个进程已调入内存的页面按先后次序链接成一个队列,并设置一个指针,称为替换指针,使它总是指向最老的页面。但该算法与进程实际运行的规律不相适应,因为在进程中,有些页面经常被访问,比如,含有全局变量、常用函数、例程等的页面,FIFO算法并不能保证这些页面不被淘汰。
#include<iostream>
#include<list>
#include<vector>
#include<iterator>
#include<fstream>
#include<algorithm>
using namespace std;
class Optimal
{
public:
int index;
int dis;
public:
friend istream & operator>>(istream & i, Optimal&o);
friend ostream & operator<<(ostream &s, const Optimal&o);
Optimal(int i)
{
this->index = i;
dis = 0;
}
Optimal()
{
dis = 0;
}
~Optimal()
{
}
bool operator<(Optimal&s)
{
if (this->dis < s.dis)
return true;
return false;
}
bool operator>(Optimal&s)
{
if (this->dis > s.dis)
return true;
return false;
}
bool operator==(const Optimal&s)
{
if (this->dis == s.dis)
return true;
return false;
}
};
istream & operator>>(istream & i, Optimal&o)
{
i >> o.index;
return i;
}
ostream & operator<<(ostream &s, const Optimal&o)
{
s << "[" << "***" << o.index << "***" << "\t" << o.dis << "]";
return s;
}
void main()
{
fstream out("data.txt");
list<Optimal> v;
list<Optimal> w;
copy(istream_iterator<Optimal>(out), istream_iterator<Optimal>(), back_inserter(v));
//copy(v.begin(),v.end(),ostream_iterator<Optimal>(cout,"\t"));
while (v.size())
{
if (w.size() < 3)
{
Optimal p = v.front();
v.pop_front();
w.push_front(p);
for (auto ib = w.begin(); ib != w.end(); ib++)
{
(*ib).dis++;
}
copy(w.begin(), w.end(), ostream_iterator<Optimal>(cout, "\t"));
cout << endl;
}
else
{
bool istrue = false;
for (auto ib = w.begin(); ib != w.end(); ib++)
{
if (ib->index == v.front().index)
{
istrue = true;
}
}
if (istrue == false)
{
list<Optimal>::iterator s = find_if(w.begin(), w.end(), [](Optimal&s)->bool{ if (s.dis == 3) { return true; }else{ return false;}});
w.remove(*s);
Optimal p = v.front();
v.pop_front();
w.push_front(p);
for (auto ib = w.begin(); ib != w.end(); ib++)
{
(*ib).dis++;
}
copy(w.begin(), w.end(), ostream_iterator<Optimal>(cout, "\t"));
cout << endl;
}
else
{
v.pop_front();
}
}
}
cin.get();
}
data.txt文件
测试结果