//顺序队列的应用
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
const int MaxPQueueSize = 100;
struct DataType
{
int tastNo;
int priority;
DataType()
{
tastNo = 0;
priority = 0;
}
};
int operator<(const DataType&a,const DataType& b)
{
return a.priority < b.priority;
}
class SeqPQueue
{
private:
DataType data[MaxPQueueSize];
int size;
public:
SeqPQueue(void)
{
size = 0;
}
~SeqPQueue(void){}
void PQInsert(const DataType&item);
DataType PQDelete(void);
DataType PQFront(void)const;
int PQueueEmpty(void)const
{
return size == 0;
}
int GetSize(void)const
{
return size;
}
void Clear(void)
{
size = 0;
}
};
void SeqPQueue::PQInsert(const DataType&item)
{
if (size == MaxPQueueSize)
{
cout<<"队列已满"<<endl;
exit(0);
}
data[size] = item;
size++;
}
//删除优先级最高的元素并由函数返回
DataType SeqPQueue::PQDelete(void)
{
if (size<=0)
{
cout<<"队列已空"<<endl;
exit(0);
}
DataType min = data[0];
int minIndex = 0;
for (int i=0;i<size;i++)
{
if (data[i]<min)
{
min = data[i];
minIndex = i;
}
}
for(int i = minIndex;i<size-1;i++)
{
data[i]=data[i+1];
}
size--;
return min;
}
//读优先级最高的元素并由函数返回
DataType SeqPQueue::PQFront(void) const
{
if (size<=0)
{
cout<<"队列已空!"<<endl;
exit(0);
}
DataType min = data[0];
int minIndex = 0;
for (int i=0;i<size;i++)
{
min = data[i];
minIndex = i;
}
return min;
}
void main()
{
SeqPQueue myPQueue;
ifstream fin;
DataType tast;
fin.open("tast.dat",ios::in|ios::_Nocreate);
if (!fin)
{
cout<<"fail "<<endl;
exit(0);
}
while (!fin.eof())
{
fin>>tast.tastNo;
fin>>tast.priority;
myPQueue.PQInsert(tast);
}
int i = 0;
cout<<"序号"<<"任务号"<<"优先级"<<endl;
while (!myPQueue.PQueueEmpty())
{
cout<<i<<" ";
tast = myPQueue.PQDelete();
cout<<tast.tastNo<<" ";
cout<<tast.priority<<endl;
i++;
}
}
at的内容为
1 30
2 10
3 40
4 20
5 0
//运行结果
0 5 0
1 2 10
2 4 20
3 1 30
4 3 40