A queue is similar to a waiting line. The item that has been in the queue the longest is the next one removed—so a queue is referred to as a first-in, first-out (FIFO) data structure. Class queue (from header <queue> ) enables insertions at the back of the underlying data structure and deletions from the front. A queue
can store its elements in objects of the Standard Library’s list
or deque
containers. By default, a queue
is implemented with a deque
. The common queue
operations are push
to insert an element at the back of the queue
(implemented by calling function push_back
of the underlying container), pop
to remove the element at the front of the queue
(implemented by calling function pop_front
of the underlying container), front to get a reference to the first element in the queue
(implemented by calling function front
of the underlying container), back to get a reference to the last element in the queue
(implemented by calling function back
of the underlying container), empty
to determine whether the queue
is empty (implemented by calling function empty
of the underlying container) and size
to get the number of elements in the queue
(implemented by calling function size
of the underlying container).
Figure 15.20 demonstrates the queue
adapter class. Line 9 instantiates a queue
of double
s. Lines 12–14 use function push
to add elements to the queue
. The while
statement in lines 19–23 uses function empty
(available in all containers) to determine whether the queue
is empty (line 19). While there are more elements in the queue
, line 21 uses queue
function front
to read (but not remove) the first element in the queue
for output. Line 22 removes the first element in the queue
with function pop
(available in all adapter classes).
1 // Fig. 15.20: fig15_20.cpp
2 // Standard Library queue adapter class template.
3 #include <iostream>
4 #include <queue> // queue adapter definition
5 using namespace std;
6
7 int main()
8 {
9 queue< double > values; // queue with doubles
10
11 // push elements onto queue values
12 values.push( 3.2 );
13 values.push( 9.8 );
14 values.push( 5.4 );
15
16 cout << "Popping from values: ";
17
18 // pop elements from queue
19 while ( !values.empty() )
20 {
21 cout << values.front() << ' '; // view front element
22 values.pop(); // remove element
23 } // end while
24
25 cout << endl;
26 } // end main
Popping from values: 3.2 9.8 5.4