4.3 Queue
4.3.1 ADT interface
operating | Features | |
---|---|---|
size() | Report the size of the queue | |
empty() | Determine whether the queue is empty | |
enqueue(e) | Insert e into the end of the line | |
dequeue() | Delete leader object | |
front() | Introduce the leader of the team |
4.3.2 Queue template class
#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 Application of Queue
4.3.3.1 Cyclic service simulation
RoundRobin {
//循环分配器
Queue Q( clients ); //共享资源的所有客户组成队列
while ( ! ServiceClosed() ) {
//在服务关闭之前,反复地
e = Q.dequeue(); //令队首的客户出队,并
serve( e ); Q.enqueue( e ); //接受服务,然后重新入队
} }
4.3.3.2 Bank service simulation
4.3.3.2.1 Define customer objects
struct Customer {
//顾客类
int window; //所属窗口(队列)
unsigned int time; //服务时长
};
4.3.3.2.2 Bank service simulation
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 Find the shortest queue
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;
}