4.3 Queue(队列)

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值