Apache C++ Standard Library User's Guide

## 10.3 The queue Data Abstraction

As a data abstraction, a queue is traditionally defined as any object that implements the following operations given in Table 17:

#### Table 17: Queue operations

Function | Implemented operation
`empty()` | Returns `true` if the collection is empty
`size()` | Returns number of elements in collection
`front()` | Returns (but does not remove) the element at the front of the queue
`back()` | Returns (but does not remove) the element at the end of the queue
`push(newElement)` | Pushes a new element on to the end of the queue
`pop()` | Removes (but does not return) the element at the front of the queue

Note that removing the element at the front of the queue does not return a value. If the value of the element is important, you must retrieve the element before you remove the element

### 10.3.1 Include Files

Programs that use the queue data abstraction should include the `queue` header file:

    #include <queue>

### 10.3.2 Declaration and Initialization of queue

A declaration for a queue must specify the element type, and can also specify the container that will hold the values. For a queue the default container is a deque, but a list can also be used. The list version is generally smaller, while the deque version may be slightly faster. The following are sample declarations for a queue:

    std::queue<int, list<int> > queueOne;
    std::queue<double> queueTwo;                       // uses a deque
    std::queue<Part*, list<Part*> > queueThree;
    std::queue<Customer, list<Customer> > queueFour;

The last example creates a queue of a user-defined type named Customer. As with the stack container, all objects stored in a queue must understand `operator<()` and `operator==()`.

Because the queue does not implement an iterator, few of the generic algorithms described in Part IV apply to queues.

### 10.3.3 Example Program: Bank Teller Simulation

> NOTE -- The complete version of the bank teller simulation program is in teller.cpp.

Queues are often found in businesses, such as supermarkets or banks. Suppose you are the manager of a bank, and you need to determine how many tellers to have working during certain hours. You decide to create a computer simulation, basing your simulation on certain observed behavior. For example, you note that during peak hours there is a ninety percent chance that a customer will arrive every minute.

We create a simulation by first defining objects to represent both customers and tellers. For customers, the information we want to know is the average amount of time they spend waiting in line. Thus, customer objects simply maintain two integer data members: the time they arrive in line, and the time they spend at the counter. The latter is a value randomly selected between 2 and 8.

    class Customer
    {
    public:

      int arrivalTime;
      int processTime;

      Customer (int at = 0)
        : arrivalTime (at),
          processTime (2 + irand () % 6) {}

      // are we done with our transaction?
      bool done () {
        return --processTime < 0;
      }

      // order by arrival time
      bool operator< (const Customer& c) const {
        return arrivalTime < c.arrivalTime;
      }
    };

Because objects can only be stored in a standard queue if they can be compared for ordering, it is necessary to define `operator<()` for customers. Customers can also tell us when they are done with their transactions. Tellers are either busy servicing customers, or they are free. Thus, each teller value holds two data members: a customer, and a boolean flag. Tellers define a member function to answer whether they are free or not, as well as a member function that is invoked when they start servicing a customer.

    class Teller
    {
    public:
      Teller (): free (true) { }

      bool isFree () {   // are we free to service new customer?
        if (free)
          return true;
        if (customer.done())
          free = true;
        return free;
      }

      // start serving new customer

      void addCustomer (const Customer &c) {
        customer = c;
        free = false;
      }

    private:

      bool     free;
      Customer customer;
    };

The main program, then, is a large loop cycling once each simulated minute. The probability is 0.9 that each minute a new customer is entered into the queue of waiting customers. Each teller is polled, and if any are free they take the next customer from the queue. Counts are maintained of the number of customers serviced and the total time they spent in queue. From these two values we can determine, following the simulation, the average time a customer spent waiting in the line.

    int main ()
    {
      const int numberOfTellers = 5;
      const int numberOfMinutes = 60;
      double totalWait          = 0;
      int numberOfCustomers     = 0;

      std::vector<Teller> teller (numberOfTellers);
      std::queue<Customer> line;

      for (int t = 0; t < numberOfMinutes; t++) {
        if (irand() % 10 < 9)
          line.push (Customer (t));

        for (int i = 0; i < numberOfTellers; i++) {
          if (teller[i].isFree () && !line.empty ()) {
            Customer& frontCustomer = line.front ();
            numberOfCustomers++;
            totalWait += t - frontCustomer.arrivalTime;
            teller[i].addCustomer (frontCustomer);
            line.pop ();
          }
        }
      }

      std::cout << "average wait: "
                << (totalWait / numberOfCustomers) << std::endl;
    }

By executing the program several times, using various values for the number of tellers, the manager can determine the smallest number of tellers that can service the customers while maintaining the average waiting time at an acceptable level.