C++ Queues

C/C++ Reference

back
Syntax:
  #include <queue>
  TYPE& back();
  const TYPE& back() const;

The back() function returns a reference to the last element in the queue.

For example:

 queue<int> q;
 for( int i = 0; i < 5; i++ ) {
   q.push(i);
 }
 cout << "The first element is " << q.front()
      << " and the last element is " << q.back() << endl;           

This code produces the following output:

 The first element is 0 and the last element is 4               

The back() function runs in constant time.

Related topics:

empty
Syntax:
  #include <queue>
  bool empty() const;

The empty() function returns true if the queue has no elements, false otherwise.

For example, the following code uses empty() as the stopping condition on a while loop to clear a queue while displaying its contents:

 queue<int> q;
 for( int i = 0; i < 5; i++ ) {
   q.push(i);
 }
 while( !q.empty() ) {
   cout << q.front() << endl;
   q.pop();
 }              
Related topics:

front
Syntax:
  #include <queue>
  TYPE& front();
  const TYPE& front() const;

The front() function returns a reference to the first element of the queue, and runs in constant time.

Related topics:

pop
Syntax:
  #include <queue>
  void pop();

The function pop() removes the first element of the queue and discards it.

Related topics:

push
Syntax:
  #include <queue>
  void push( const TYPE& val );

The function push() adds val to the end of the current queue.

For example, the following code uses the push() function to add ten integers to the end of a queue:

   queue<int> q;
   for( int i=0; i < 10; i++ ) {
     q.push(i);
   }
Related topics:

Queue constructor
Syntax:
  #include <queue>
  queue();
  queue( const Container& con );

Queues have a default constructor as well as a copy constructor that will create a new queue out of the container con.

For example, the following code creates a queue of strings, populates it with input from the user, and then displays it back to the user:

  queue<string> waiting_line;
  while( waiting_line.size() < 5 ) {
    cout << "Welcome to the line, please enter your name: ";
    string s;
    getline( cin, s );
    waiting_line.push(s);
  }

  while( !waiting_line.empty() ) {
    cout << "Now serving: " << waiting_line.front() << endl;
    waiting_line.pop();
  }

When run, the above code might produce this output:

  Welcome to the line, please enter your name: Nate
  Welcome to the line, please enter your name: lizzy 
  Welcome to the line, please enter your name: Robert B. Parker
  Welcome to the line, please enter your name: ralph
  Welcome to the line, please enter your name: Matthew
  Now serving: Nate
  Now serving: lizzy
  Now serving: Robert B. Parker
  Now serving: ralph
  Now serving: Matthew

size
Syntax:
  #include <queue>
  size_type size() const;

The size() function returns the number of elements in the current queue.

Related topics: