Chapter 3 Queues Content Points  Definitions Definitions  Implementations of Queues Implementations of Queues  Circular Implementation of Queues in.

Slides:



Advertisements
Similar presentations
Chapter 6 Queues and Deques.
Advertisements

Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
纺纱学. 2 绪 论 基本要求:了解纺纱系统的类别 重点掌握:棉纺系统的工艺流程 3 一、纺纱原理与设备 纺纱:用物理或机械的方法将纺织纤维纺成纱 线的过程。 纺纱原理:初加工、原料的选配、开松除杂、 混和、梳理、精梳、并合、牵伸、加捻、卷绕等。 纺纱方法:传统纺纱方法、新型纺纱方法。 纺纱设备:开清棉联合机、梳棉机、精梳机、
第十二章 常微分方程 返回. 一、主要内容 基本概念 一阶方程 类 型 1. 直接积分法 2. 可分离变量 3. 齐次方程 4. 可化为齐次 方程 5. 全微分方程 6. 线性方程 类 型 1. 直接积分法 2. 可分离变量 3. 齐次方程 4. 可化为齐次 方程 5. 全微分方程 6. 线性方程.
1 Data Structures CSCI 132, Spring 2014 Lecture 8 Implementing Queues.
CHAPTER 4 QUEUE CSEB324 DATA STRUCTURES & ALGORITHM.
队列. Queues 队列 队列 (Queues) 是生活中 “ 排队 ” 的抽象。队列 的特点是: – 一些元素的线形序列; – 新加入的元素排在队尾,出队的元素在对头 进行,即插入和删除只能在队的两段进行; – 先来的先得到服务;故称为先进先出表 (FIFO, first in first.
1. Specifications for Queues
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
Chapter3 QUEUES.
1 CSC 211 Data Structures Lecture 22 Dr. Iftikhar Azim Niaz 1.
DATA STRUCTURE & ALGORITHMS
Data Structures Chapter 3 Queues Andreas Savva. 2 Queues A data structure modeled after a line of people waiting to be served. A data structure modeled.
概率统计( ZYH ) 节目录 2.1 随机变量与分布函数 2.2 离散型随机变量的概率分布 2.3 连续型随机变量的概率分布 第二章 随机变量及其分布.
Chapter 7 Queues. © 2005 Pearson Addison-Wesley. All rights reserved7-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Queues Chapter 6. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
地理信息系统概述. 数据和信息 (Data & Information) 数据 原始事实 如:员工姓名, 数据可以有数值、图形、声音、视觉数据等 信息 以一定规则组织在一起的事实的集合。
1 为了更好的揭示随机现象的规律性并 利用数学工具描述其规律, 有必要引入随 机变量来描述随机试验的不同结果 例 电话总机某段时间内接到的电话次数, 可用一个变量 X 来描述 例 检测一件产品可能出现的两个结果, 也可以用一个变量来描述 第五章 随机变量及其分布函数.
线性代数习题课 吉林大学 术洪亮 第一讲 行 列 式 前面我们已经学习了关 于行列式的概念和一些基本 理论,其主要内容可概括为:
数 学 系 University of Science and Technology of China DEPARTMENT OF MATHEMATICS 第 3 章 曲线拟合的最小二乘法 给出一组离散点,确定一个函数逼近原函数,插值是这样的一种手段。 在实际中,数据不可避免的会有误差,插值函数会将这些误差也包括在内。
实验三: 用双线性变换法设计 IIR 数字滤波器 一、实验目的 1 熟悉用双线性变换法设计 IIR 数字滤波器的原理与方法。 2 掌握数字滤波器的计算机仿真方法。 3 通过观察对实际心电图信号的滤波作用, 获得数字滤波的感性知 识。
第二章 贝叶斯决策理论 3学时.
Queues Chapter 6. Chapter 6: Queues2 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface.
Chapter 7 Queues. © 2005 Pearson Addison-Wesley. All rights reserved7-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
编译原理总结. 基本概念  编译器 、解释器  编译过程 、各过程的功能  编译器在程序执行过程中的作用  编译器的实现途径.
 符号表  标识符的作用: 声明部分:定义了各种对象及对应的属性和 使用规则。 程序体:对所定义的对象进行各种操作。 $ididname IdnameAttributeIR  必要性 Token : 新表-符号表(种类、类型等信息):
首 页 首 页 上一页 下一页 本讲内容本讲内容 视图,剖视图(Ⅰ) 复习: P107 ~ P115 作业: P48(6-2,6-4), P49( 去 6-6) P50, P51(6-13), P52 P50, P51(6-13), P52 P53 (6-18,6-20) P53 (6-18,6-20)
CHP-4 QUEUE.
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
TK1924 Program Design & Problem Solving Session 2011/2012 L6: Queues.
《 UML 分析与设计》 交互概述图 授课人:唐一韬. 知 识 图 谱知 识 图 谱知 识 图 谱知 识 图 谱.
Queues Chapter 3. Objectives Introduce the queue abstract data type. – Queue methods – FIFO structures Discuss inheritance in object oriented programming.
ATLAS computing status in IHEP Erming Pei, CC-IHEP Yangzhou, May 15’ th 2009.
Data Structures Using C++ 2E Chapter 8 Queues. Data Structures Using C++ 2E2 Objectives Learn about queues Examine various queue operations Learn how.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 3)
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Queues Chapter 6. Chapter 6: Queues Chapter Objectives To learn how to represent a waiting line (queue) and how to use the five methods in the Queue interface:
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
Introduction to Stacks Chapter 2. Objectives Introduce abstract data types. Discuss implementation types. – Static – Dynamic – Contiguous Introduce the.
项目七: PLC 功能指令应用 带进位循环左移指令 XXXXX. 项目七: PLC 功能指令应用 FX2 系列可编程控制器移位控制指令有移位、循环移位、字移位 及先进先出 FIFO 指令等 10 条指令。 带进位循环右移指令 RCR 带进位循环左移指令 RCL 字右移位指令 WSFR 先入先出读出指令.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
表单自定义 “ 表单自定义 ” 功能是用于制作表单的 工具,用数飞 OA 提供的表单自定义 功能能够快速制作出内容丰富、格 式规范、美观的表单。
The Abstract Data Type Queue A queue New items enter at the back, or rear, of the queue Items leave from the front of the queue First-in, first-out (FIFO)
Data Structures & Algorithms
力的合成 力的合成 一、力的合成 二、力的平行四边形 上一页下一页 目 录 退 出. 一、力的合成 O. O. 1. 合力与分力 我们常常用 一个力来代替几个力。如果这个 力单独作用在物体上的效果与原 来几个力共同作用在物体上的效 果完全一样,那么,这一个力就 叫做那几个力的合力,而那几个 力就是这个力的分力。
Chapter 8 Queues. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Kruse/Ryba ch031 Object Oriented Data Structures Queues Implementations of Queues Circular Implementation of Queues.
Kruse/Ryba ch031 Object Oriented Data Structures Queues Implementations of Queues Circular Implementation of Queues.
Chapter 7 Queues Introduction Queue applications Implementations.
U niversity of S cience and T echnology of C hina VxWorks 及其应用开发 陈香兰 年 7 月.
Prof. Qing Wang Lecture 5 Stack and Queue Lecture Notes: Data Structures and Algorithms.
3D 仿真机房建模 哈尔滨工业大学 指导教师:吴勃英、张达治 蒋灿、杜科材、魏世银 机房尺寸介绍.
Queues Another Linear ADT Copyright © 2009 Curt Hill.
1 第三章 数列 数列的概念 考点 搜索 ●数列的概念 ●数列通项公式的求解方法 ●用函数的观点理解数列 高考 猜想 以递推数列、新情境下的 数列为载体, 重点考查数列的通 项及性质, 是近年来高考的热点, 也是考题难点之所在.
第二章 线性表 第二节 线性链表 5. 线性表的链式表示 顺序表的优点是可以随机选取表中元素 缺点是插入删除操作复杂。 用指针将互不相连的内存结点串成的 线性表叫线性链表。 结点 node 由一个数据元素域,一个或几个 指针域组成。单链表的结点只有一个指针域。
目录 上页 下页 返回 结束 二、无界函数反常积分的审敛法 * 第五节 反常积分 无穷限的反常积分 无界函数的反常积分 一、无穷限反常积分的审敛法 反常积分的审敛法  函数 第五章 第五章.
1 Data Structures CSCI 132, Spring 2014 Lecture 7 Queues.
SME.USTB Human Factors 人机工程学 By Wei Dong Department of Industry Design, SME, USTB.
Session 03 - Templates Outline 03.1Introduction 03.2Function Templates 03.3Overloading Template Functions 03.4Class Templates 03.5Class Templates and Non-type.
Review Array Array Elements Accessing array elements
Data Structures Using C++ 2E
CC 215 Data Structures Queue ADT
Queues.
تهیه کنندگان مهری بابائی،گیتا جوادی رضا امید ملایری ،ناصر بهمدی
Using a Queue Chapter 8 introduces the queue data type.
Using a Queue Chapter 8 introduces the queue data type.
CSCS-200 Data Structure and Algorithms
Presentation transcript:

Chapter 3 Queues

Content Points  Definitions Definitions  Implementations of Queues Implementations of Queues  Circular Implementation of Queues in C++ Circular Implementation of Queues in C++  Demonstration and TestingDemonstration and Testing  Application of Queues:Simulation Application of Queues:Simulation

A queue is a data structure modeled after a line of people waiting to be served. Along with stacks, queues are one of the simplest kinds of data structures. This chapter develops properties of queues, studies how they are applied, and examines different implementations. The implementations illustrate the use of derived classes in C++ and the important object-oriented technique of class inheritance. 队列是一个模拟日常生活中人们排队等候服务的 数据结构。与栈一样,队列是最简单的数据结构。 本章描述了队列的性质、应用及不同的实现方法。 描述了 C++ 中派生类的使用和类的继承中重要的 面向对象技术。

Definitions  Queue : we similarly define a queue to be a list in which all additions to the list are made at one end, and all deletions from the list are made at the other end.  Queues are also called first-in, first-out lists, or FIFO (先进先出 表) for short. Applications: a computer system,queues of tasks waiting for printer,disk storage,with multitasking , use of the CPU. Front: the first entry in the queue rear: the last entry in the queue front (head) rear (tail)

Queue Operations (队列的基本操作)  As in our treatment of stacks, we shall implement queues whose entries have a generic type, which we call Queue_entry. Queue :: Queue( ); postcondition: The Queue has been created and is initialized to be empty.

Error_code Queue :: append(const Queue_entry &x); postcondition: If there is space, x is added to the Queue as its rear. Otherwise an Error_code of overflow is returned. Error_code Queue :: serve( ); postcondition: If the Queue is not empty, the front of the Queue has been removed.Otherwise an Error_code of underflow is returned. Queue Operations (队列的基本操作)

Error_code Queue :: retrieve(Queue_entry &x) const; postcondition: If the Queue is not empty, the front of the Queue has been recorded as x. Otherwise an Error_code of underflow is returned. (取队头元素) bool Queue :: empty( ) const; postcondition: Return true if the Queue is empty, otherwise return false. Queue Operations (队列的基本操作)

class Queue { public: Queue( ); bool empty( ) const; Error_code append(const Queue_entry &x); Error_code serve( ); Error_code retrieve(Queue_entry &x) const; // Additional members will represent queue data. }; Queue Operations (队列的基本操作) Remove front or underflow Record front as x or underflow push pop front Add x to rear or overflow

Extended Queue Operations Extended Queue Operations: fullclearsizeserve_and_retrieve class Queue methods: Queue (constructor) append serve retrieve empty data members class Queue class Extended_Queue methods: Extended_queue (constructor) append serve retrieve empty full clear size serve_and_retrieve data members additional data members inheritance Base class Derived class

Extended Queue Operations class Extended_queue: public Queue { public: bool full( ) const; int size( ) const; void clear( ); Error_code serve_and_retrieve(Queue_entry &item); };

Extended Queue Operations  The new operations for our class Extended_queue have the following specifications. bool Extended_queue :: full( ) const; postcondition: Return true if the Extended_queue is full; return false otherwise. void Extended_queue :: clear( ); postcondition: All entries in the Extended_queue have been removed; it is now empty.

Extended Queue Operations int Extended_queue :: size( ) const; postcondition: Return the number of entries in the Extended_queue. Error_code Extended_queue :: serve_and_retrieve(Queue_entry &item); postcondition: Return underflow if the Extended_queue is empty. Otherwise remove and copy the item at the front of the Extended_queue to item and return success.

Extended Queue Operations Every A “is a” B class A is derived from class B Every A “has a” B class A has a data member of type B  The relationship between the class Extended_queue and the class Queue is often called an is-a relationship.  This is because every Extended_queue object “is a” Queue object with other features—namely, the methods serve_and_retrieve, full,size, and clear.

As another illustration of the is-a relationship between classes, consider C++ classes that might be used in a program to manage a university budget. Some of these classes are University, Student, University_president, and Person. Every student is a person, and therefore we might create the class Student as derived from the class Person to reflect the is-a relationship between the corresponding concepts. The class University_president could also be implemented as a derived class of Person to reflect another obvious is-a relationship. The classes University and University_president do not reflect an is-a relationship, however the classes are related, because every university does have a president. We shall say that these classes reflect a has-a relationship, and in an implementation we would make this relationship clear by layering the classes, that is, by including a data member of type University_president in the definition of the class University.

Home work P84 exercise E2 E3(b)(e)

IMPLEMENTATIONS OF QUEUES (队列的实现).  The Physical Model (物理模型) One strategy (策略) would be to keep the front of the queue always in the first location of the array. Then an entry could be appended to the queue simply by increasing the counter showing the rear, in exactly the same way as we added an entry to a stack. To remove an entry from the queue,however, would be very expensive indeed.

IMPLEMENTATIONS OF QUEUES (队列的实现).  Linear Implementation (队列的顺序实现) To append an entry to the queue, we simply increase the rear by one and put the entry in that position. To serve an entry, we take it from the position at the front and then increase the front by one. Job 1Job 2Job 3Job 4Job 5Job 6Job 7 1  append Job 1  append Job 2  append Job 3  serve Job 1  append Job 4  append Job 5  append Job 6  serve Job 2  append Job 7  append Job 8

fault:discarded space This method has a major defect (缺点) : Both the front and rear indices are increased but never decreased. as the queue moves down the array, the storage space at the beginning of the array is discarded (丢弃) and never used again. Advantage:for applications where the queue is regularly emptied(such as when a series of requests is allowed to build up to a certain point, and then a task is initiated that clears all the requests before returning), then at a time when the queue is empty, the front and rear can both be reset to the beginning of the array, and the simple scheme of using two indices and straight-line storage becomes a very efficient implementation.

IMPLEMENTATIONS OF QUEUES (队列的实现).  Circular Arrays (顺序循环队列) In concept, we can overcome the inefficient use of space simply by thinking of the array as a circle rather than a straight line. At different times, the queue will occupy different parts of the array, but we never need worry about running out of space unless the array is fully occupied,in which case we truly have overflow.

IMPLEMENTATIONS OF QUEUES.

[ 5 ] [ 4] [ 3 ][ 2 ] [ 1 ] [ 0 ] [ 5 ] [ 4] [ 3 ][ 2 ] [ 1 ] [ 0 ]

IMPLEMENTATIONS OF QUEUES.  Implementation of Circular Arrays (循环队列的实现) Our next problem is to implement a circular array as an ordinary linear (that is, straight-line) array. To do so, we think of the positions around the circle as numbered from 0 to max - 1, where max is the total number of entries in the circular array, and to implement the circular array, we use the same numbered entries of a linear array. Then moving the indices is just the same as doing modular arithmetic When we increase an index past max - 1,we start over again at 0. This is like doing arithmetic on a circular clock face; the hours are numbered from 1 to 12, and if we add four hours to ten o’clock, we obtain two o’clock.

IMPLEMENTATIONS OF QUEUES.  Circular Arrays in C++ In C++, we can increase an index i of a circular array by using the ternary operator ? : and writing i = ((i + 1) == max) ? 0 : (i + 1); Or we can use the modulus operator and write i = (i + 1) % max You should check to verify that the result of the latter expression is always between 0 and max-1.

IMPLEMENTATIONS OF QUEUES.  Boundary Conditions (边界条件) 存在问题 : 如何区别队空和队满?

IMPLEMENTATIONS OF QUEUES.  Possible Solutions (解决方法) empty position (少用一个空间) One is to insist on leaving one empty position in the array, so that the queue is considered full when the rear index has moved within two positions of the front. flag (设定标志位) A second method is to introduce a new variable. This can be a Boolean flag that is set as true when the rear comes just before the front to indicate that the queue is full or an integer variable that counts the number of entries in the queue. special values (采用特殊值) The third method is to set one or both of the indices to some value(s) that would otherwise never occur in order to indicate an empty (or full) queue. For example, an empty queue could be indicated by setting the rear index to -1.

IMPLEMENTATIONS OF QUEUES.  Summary of Implementations To summarize the discussion of queues, let us list all the methods we have discussed for implementing queues. The physical model: a linear array with the front always in the first position and all entries moved up the array whenever the front is removed. This is generally a poor method for use in computers. A linear array with two indices always increasing. This is a good method if the queue can be emptied all at once. A circular array with front and rear indices and one position left vacant.

IMPLEMENTATIONS OF QUEUES.  Summary of Implementations A circular array with front and rear indices and a flag to indicate fullness (or emptiness). A circular array with front and rear indices and an integer variable counting entries. A circular array with front and rear indices taking special values to indicate emptiness.

CIRCULAR IMPLEMENTATION OF QUEUES IN C++ (循环队列实现).  The implementation in a circular array which uses a counter to keep track of the number of entries in the queue both illustrates techniques for handling circular arrays and simplifies the programming of some of the extended-queue operations.  We shall take the queue as stored in an array indexed with the range 0 to (maxqueue - 1)

CIRCULAR IMPLEMENTATION OF QUEUES IN C++. const int maxqueue = 10; // small value for testing class Queue { public: Queue( ); bool empty( ) const; Error_code serve( ); Error_code append(const Queue_entry &item); Error_code retrieve(Queue_entry &item) const; protected: int count; int front, rear; Queue_entry entry[maxqueue]; };

CIRCULAR IMPLEMENTATION OF QUEUES IN C++. Queue :: Queue( ) /* Post: The Queue is initialized to be empty. */ { count = 0; rear = maxqueue - 1; front = 0; } bool Queue :: empty( ) const /* Post: Return true if the Queue is empty, otherwise return false. */ { return count == 0; }

CIRCULAR IMPLEMENTATION OF QUEUES IN C++. Error_code Queue :: append(const Queue_entry &item) /* Post: item is added to the rear of the Queue. If the Queue is full return an Error_code of overflow and leave the Queue unchanged. */ { if (count >= maxqueue) return overflow; count++; rear = ((rear + 1) == maxqueue) ? 0 : (rear + 1); entry[rear] = item; return success; }

CIRCULAR IMPLEMENTATION OF QUEUES IN C++. Error_code Queue :: serve( ) /* Post: The front of the Queue is removed. If the Queue is empty return an Error_code of underflow. */ { if (count <= 0) return underflow; count--; front = ((front + 1) == maxqueue) ? 0 : (front + 1); return success; }

CIRCULAR IMPLEMENTATION OF QUEUES IN C++ Error_code Queue :: retrieve(Queue_entry &item) const /* Post: The front of the Queue retrieved to the output parameter item. If the Queue is empty return an Error_code of underflow. */ { if (count <= 0) return underflow; item = entry[front]; return success; } int Extended_queue :: size( ) const /* Post: Return the number of entries in the Extended_queue. */ { return count; }

DEMONSTRATION AND TESTING  Menu-driven demonstration program int main( ) /* Post: Accepts commands from user as a menu-driven demonstration program for the class Extended_queue. Uses: The class Extended_queue and the functions introduction, get_command,and do_command. */ { Extended_queue test_queue; introduction( ); while (do_command(get_command( ), test_queue)); }

DEMONSTRATION AND TESTING  Menu-driven demonstration program

DEMONSTRATION AND TESTING  Menu-driven demonstration program

DEMONSTRATION AND TESTING void help( ) /* Post: A help screen for the program is printed, giving the meaning of each command that the user may enter. */ { cout << endl << "This program allows the user to enter one command" << endl << "(but only one) on each input line." << endl << "For example, if the command S is entered, then" << endl << "the program will serve the front of the queue." << endl << endl << " The valid commands are:" << endl << "A - Append the next input character to the extended queue" << endl

DEMONSTRATION AND TESTING << "S - Serve the front of the extended queue" << endl << "R - Retrieve and print the front entry." << endl << "# - The current size of the extended queue" << endl << "C - Clear the extended queue (same as delete)" << endl << "P - Print the extended queue" << endl << "H - This help screen" << endl << "Q - Quit" << endl to continue." << flush; char c; do { cin.get(c); } while (c != ‘\n’); }

DEMONSTRATION AND TESTING bool do_command(char c, Extended_queue &test_queue) /* Pre: c represents a valid command. Post: Performs the given command c on the Extended_queue test_queue. Returns false if c == ‘q’, otherwise returns true. Uses: The class Extended_queue. */ { bool continue_input = true; Queue_entry x;

DEMONSTRATION AND TESTING switch (c) { case ’ r’: if (test_queue.retrieve(x) == underflow) cout << "Queue is empty." << endl; else cout << endl<< "The first entry is: " << x<< endl; break; case ’q’: cout << "Extended queue demonstration finished." << endl; continue_input = false; break; // Additional cases will cover other commands. } return continue_input; }

1 、 A circular queue has the problem in which it is not easy to distinguish between full and empty queues. Draw two situations to illustrate this point. The front and rear pointers should be in the same position in each situation. 2 、 Evaluate the following sentence if it is true or false and simply explain why? A queue is a FILO data structure. An array based queue implementation is usually implemented as a circular queue. An array based queue is better than a linked list implementation of a queue.

APPLICATION OF QUEUES: SIMULATION  Introduction Simulation is the use of one system to imitate the behavior of another system.Simulations are often used when it would be too expensive or dangerous to experiment with the real system. 仿真 是指用一个系统模拟另一个系统的行为。经常使用于实际系统比较昂 贵或危险的情形。 Such as :wind tunnel 、 flight simulators computer simulation: uses the steps of a program to imitate the behavior of the system under study..

In a computer simulation, the objects being studied are usually represented as data, often as data structures given by classes whose members describe the properties of the objects. Actions being studied are represented as methods of the classes. And the rules describing these actions are translated into computer algorithms. By changing the values of the data or by modifying these algorithms,we can observe the changes in the computer simulation, and then we can draw worthwhile inferences concerning the behavior of the actual system.( 可以得到关于实 际系统的有价值的结论 ) APPLICATION OF QUEUES: SIMULATION

CIRCULAR IMPLEMENTATION OF QUEUES IN C++ The same runway is used for both landings and takeoffs. (跑道可以用来降落,也可以起飞。) One plane can land or take off in a unit of time, but not both. (在单位时间内,一辆飞机可以起飞或降落。) A random number of planes arrive in each time unit. (每单位时间内,到达的飞机数目是随机的。 A plane waiting to land goes before one waiting to take off. (降落优先) The planes that are waiting are kept in queues landing and takeoff, both of which have a strictly limited size. (等待起飞或降落的飞机数目是有限制的)

APPLICATION OF QUEUES: IMULATION  class Plane (飞机类) In simulating the airport, it will be useful to create a class Plane whose objects represent individual planes. This class will definitely need an initialization method and methods to represent takeoff and landing. Moreover, when we write the main program for the simulation, the need for other Plane methods will become apparent.  class Runway (跑道类) We will also use a class Runway to hold information about the state and operation of the runway. This class will maintain members representing queues of planes waiting to land and take off.  class Random (随机数类 ) We shall need one other class in our simulation, a class Random to encapsulate the random nature of plane arrivals and departures from the runway. We shall discuss this class in more detail in Section

APPLICATION OF QUEUES: SIMULATION int main( ) // Airport simulation program /* Pre: The user must supply the number of time intervals the simulation is to run,the expected number of planes arriving, the expected number of planes departing per time interval, and the maximum allowed size for runway queues. Post: The program performs a random simulation of the airport, showing the status of the runway at each time interval, and prints out a summary of airport operation at the conclusion. Uses: Classes Runway, Plane, Random and functions run_idle, initialize. */

APPLICATION OF QUEUES: SIMULATION { int end_time; // time to run simulation int queue_limit; // size of Runway queues int flight_number = 0; double arrival_rate, departure_rate; initialize(end_time, queue_limit, arrival_rate, departure_rate); Random variable; Runway small_airport(queue_limit); for (int current_time = 0; current_time < end_time; current_time++) { // loop over time intervals int number_arrivals = variable.poisson(arrival_rate); // current arrival requests

APPLICATION OF QUEUES: SIMULATION for (int i = 0; i < number_arrivals; i++) { Plane current_plane(flight_number++, current_time, arriving); if (small_airport.can_land(current_plane) != success) current_plane.refuse( ); } int number_departures = variable.poisson(departure_rate); // current departure requests for (int j = 0; j < number_departures; j++) { Plane current_plane(flight_number++, current_time, departing); if (small_airport.can_depart(current_plane) != success) current_plane.refuse( ); }

APPLICATION OF QUEUES: IMULATION Plane moving_plane; switch (small_airport.activity(current_time, moving_plane)) { // Let at most one Plane onto the Runway at current_time. case land: moving_plane.land(current_time); break; case takeoff: moving_plane.fly(current_time); break; case idle: run_idle(current_time); } small_airport.shut_down(end_time); }

enum Runway_activity {idle, land, takeoff}; class Runway { public: Runway(int limit); Error_code can_land(const Plane &current); Error_code can_depart(const Plane &current); Runway_activity activity(int time, Plane &moving); void shut_down(int time) const; private: Extended_queue landing; Extended_queue takeoff; int queue_limit; int num_land_requests; // number of planes asking to land int num_takeoff_requests; // number of planes asking to take off int num_landings; // number of planes that have landed int num_takeoffs; // number of planes that have taken off int num_land_accepted; // number of planes queued to land int num_takeoff_accepted; // number of planes queued to take off int num_land_refused; // number of landing planes refused int num_takeoff_refused; // number of departing planes refused int land_wait; // total time of planes waiting to land int takeoff_wait; // total time of planes waiting to take off int idle_time; // total time runway is idle };

enum Plane_status {null, arriving, departing}; class Plane { public: Plane( ); Plane(int flt, int time, Plane_status status); void refuse( ) const; void land(int time) const; void fly(int time) const; int started( ) const; private: int flt_num; int clock_start; Plane_status state; };

Home work P91 E5 E6 E8

POINTERS AND PITFALLS  Before choosing implementations, be sure that all the data structures and their associated operations are fully specified on the abstract level.  In choosing between implementations, consider the necessary operations on the data structure.  If every object of class A has all the properties of an object of class B, implement class A as a derived class of B.  Consider the requirements of derived classes when declaring the members of a base class.  Implement is-a relationships between classes by using public inheritance.  Implement has-a relationships between classes by layering.  Use Poisson random variables to model random event occurrences.