4.3 Queue(队列)
4.3.1 ADT接口
操作 | 功能 | |
---|---|---|
size() | 报告队列的规模 | |
empty() | 判断队列是否为空 | |
enqueue(e) | 将e插入队尾 | |
dequeue() | 删除队首对象 | |
front() | 引入队首对象 |
4.3.2 Queue模板类
#include"List.h"
#include<iostream>
using namespace std;
template <typename T> class Queue: public List<T> { //由列表派生的队列模板类
public: //size()与empty()直接沿用
void enqueue( T const & e ) { List<T>::insertAsLast( e ); } //入队
T dequeue() { return List<T>::remove( List<T>::first() ); } //出队
T & front() { return (List<T>::first())->data; } //队首
}; //以列表首/末端为队列头/尾——颠倒过来呢?
int main()
{
Queue<int> q;
for(int i=1;i<=10;i++){
q.enqueue(i);
int temp=q.front();
cout<<i<<endl;
q.dequeue();
}
}
4.3.3 Queue 的应用
4.3.3.1 循环服务模拟
RoundRobin { //循环分配器
Queue Q( clients ); //共享资源的所有客户组成队列
while ( ! ServiceClosed() ) { //在服务关闭之前,反复地
e = Q.dequeue(); //令队首的客户出队,并
serve( e ); Q.enqueue( e ); //接受服务,然后重新入队
} }
4.3.3.2 银行服务模拟
4.3.3.2.1 定义顾客对象
struct Customer { //顾客类
int window; //所属窗口(队列)
unsigned int time; //服务时长
};
4.3.3.2.2 银行服务模拟
void simulate( int nWin, int servTime ) {
Queue<Customer> * windows = new Queue<Customer>[ nWin ];
for ( int now = 0; now < servTime; now++ ) { //在下班之前,每隔单位时间
Customer c ; c.time = 1 + rand() % 50; //一位新顾客到达,其服务时长随机指定
c.window = bestWindow( windows, nWin ); //找出最佳(最短)服务窗口
windows[ c.window ].enqueue( c ); //新顾客加入对应的队列
for ( int i = 0; i < nWin; i++ ) //分别检查
if ( ! windows[ i ].empty() ) //各非空队列
if ( -- windows[ i ].front().time <= 0 ) //队首顾客接受服务
windows[ i ].dequeue(); //服务完毕则出列,由后继顾客接替
} //for
delete [] windows; //释放所有队列
}
4.3.3.2.3 查找最短队列
int bestWindow(Queue<Customer>windows[],int nWin)
{
int minSize=windows[0].size(),optiWin=0;//最优队列(窗口)
for(int i=1;i<nWin;i++){
if(minSize>windows[i].size())//挑选出
{
minSize=windows[i].size();optiWin=i;//队列最短者
}
}
return optiWin;
}