您的位置:首页 > 其它

实验四 04彭得源

2015-06-25 08:44 176 查看


#include <iostream>
#include <list>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <time.h>
using namespace std;
struct block{
int begin,end;
};

struct free_place{
int begin,length;
};

bool cmp(const block &b1,const block &b2){
if(b1.begin<b2.begin)
return true;
return false;
}

bool cmp1(const free_place &f1,const free_place &f2){
if(f1.begin<f2.begin)
return true;
return false;
}

vector<block> memory_tab;
list<free_place> free_list;
void init(){
srand(time(0));
cout<<"请输入初始状态"<<endl;
cout<<"请输入内存占用情况"<<endl;
block now;
while(cin>>now.begin>>now.end,now.begin!=now.end){
memory_tab.push_back(now);
}
vector<free_place> v;
free_place now1;
cout<<"请输入空闲区表"<<endl;
while(cin>>now1.begin>>now1.length,now1.begin!=now1.length){
v.push_back(now1);
}
sort(memory_tab.begin(),memory_tab.end(),cmp);
sort(v.begin(),v.end(),cmp1);
for(int i=0;i<v.size();i++)
free_list.push_back(v[i]);
}
int  request(){
cout<<"请输入要申请的内存空间"<<endl;
int len;
cin>>len;
return len;
}

void print_page(){
cout<<"内存空间占用"<<endl;
for(int i=0;i<memory_tab.size();i++){
cout<<i<<":"<<memory_tab[i].begin<<"--"<<memory_tab[i].end<<endl;
}
cout<<endl;
}
void print_free_table(){
cout<<"空闲分区表"<<endl
<<"起始长度      长度"<<endl;
list<free_place>::iterator p=free_list.begin();
while(p!=free_list.end()){
cout<<(*p).begin<<"        "<<(*p).length<<endl;
p++;
}
cout<<endl;
}
void print(){
cout<<endl<<endl<<endl<<"分配结果"<<endl;
print_page();
print_free_table();
cout<<endl;
}

bool mem_get_back(block &c){
vector<block>::iterator sel;
int t;
if(memory_tab.size()!=0){
t=rand()%memory_tab.size();
while(t==0)
t=rand()%memory_tab.size();
sel=memory_tab.begin()+t;
c=*sel;
memory_tab.erase(sel);
return true;
}
return false;
}
void mem_free(block c){
free_place t;
t.begin=c.begin;
t.length=c.end-c.begin;
if(free_list.size()==0){
free_list.push_back(t);
return ;
}
if(c.begin<(*free_list.begin()).begin){
free_list.push_front(t);
}
else{
list<free_place>::iterator p=free_list.begin();
for(p++;p!=free_list.end();p++){
if(c.begin<(*p).begin){
free_list.insert(p,t);
}
}
list<free_place>::iterator q;
for(p=free_list.begin();p!=free_list.end();p++){
q=p;
++q;
if(q!=free_list.end()&&((*p).begin+(*p).length)==(*q).begin){
(*p).length+=(*q).length;
free_list.erase(q);
}
}
}
}
bool memory_pack(int length){
list<free_place>::iterator p=free_list.begin();
while(p!=free_list.end()){
if((*p).length>=length){
block c;
c.begin=(*p).begin;
c.end=c.begin+length;
memory_tab.push_back(c);
if((*p).length>length)
(*p).begin=c.end+1;
else free_list.erase(p);
sort(memory_tab.begin(),memory_tab.end(),cmp);
return true;
}
p++;
}
return false;
}
int main(){
init();
int length;
block c;
while(1){
length=request();
if(length){
if(mem_get_back(c))
mem_free(c);
if(memory_pack(length))
print();
else cout<<"内存不足"<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: