QUEUE  

Queue is a container adaptor.  A queue adaptor transforms a sequence container into a first-in, first-out queue. Elements are inserted on one end and removed from the opposite end, which is called FIFO service.  Elements cannot be accessed in any other fashion.

To use queue class include <queue>.

The template specification for queue:

template <class T, class Container=deque <T> > class queue

where T is  the type of data being stored and Container is the type of container used to hold the queue, which by default is deque.

STL provides a queue container adaptor that can be applied to any container that supports the following operations:

Queue adaptor cannot be applied to vector because vector does not support pop_front(). All these operations are provided by list and deque. Thus, lists and deques are used as containers for a queue. 

The queue adaptor has the following constructor:

explicit queue (const Container &cnt = Container());  

The queue() constructor creates an empty queue.

The queue class defines comparison operators:

==, <, <=, !=, >, >=

Because a queue is a controlled sequence, you cannot obtain an iterator to a queue. Nor you can access a queue via the [ ] operator.  Although you cannot cycle through the contents of a queue via an iterator or access its elements out of sequence, it is possible to enumerate the contents of a queue by repeatedly removing the front element and pushing it onto the rear of the queue until all elements have been examined.

Member functions of queue:  

Member

Description

value_type &front();

Returns a reference to the first element in the queue

value_type &back();

Returns a reference to the last element in the queue

bool empty () const

Returns true if the queue contains no elements.

void pop ();

Removes the first element in the queue

void push (const T &val);

Adds an element with the value specified by val to the end of the queue.

size_type size () const;

Returns the number of elements currently in the queue.

 Example:

#include <queue>
#include <string>
#include <iterator>
#include <assert.h>
#include <iostream>
using namespace std;

main() {
    queue<int> qi;
    queue<string> qs;

    for(int i = 0; i < 20; i++)
        qi.push(i);
    assert(!qi.empty());

    cout<<"Removing elements in range 1 through 7...\n";
    for(i = 0; i < 8; i++) {
        cout<<qi.front()<<" is removed\n";
        qi.pop();
    }
    cout<<endl;

    cout<<"Removing all elements...\n";
    while(!qi.empty()) {
        cout<<qi.front()<<" is removed\n";
        qi.pop();
    }
    assert(qi.empty());

    assert(qs.empty());
    qs.push("John");
    qs.push("Tom");
    qs.push("Jane");
    qs.push("Anna");
    assert(!qs.empty());

    // remove last element
    qs.pop(); 

    return 0;
}