The container queue

The characteristics of the container queue

The container of type queue is similar to the container std::stack. Like the stack, we can only add elements at the end of the queue. However, unlike containers of type stack, we can access both the first and last element of the queue and we can only remove the first one.

Containers of type queue are often visualized as a queue of people. People can only join the queue from the end of it (At least, they are supposed to) and people leave the queue only from its beginning (If we consider all the members of the queue are perfectly patient).

Like the other containers, the class std::queue takes, in template argument, the type of the objects (or primitives) it holds.

Its methods

Here is a table with the methods of the container std::queue<T>:

MethodDescription
bool empty() constReturns true only if the queue is empty.
size_type size() constReturns the number of elements inside the queue.
T & front()<br>const T & front() constReturns a reference to the first element of the queue.
T & back()<br>const T & back() constReturns a reference to the last element of the queue.
void push(const T & elem)<br>void push(T && elem) // C++11Adds an element at the end of the queue.
void emplace(Args &&... args) // C++11Constructs a new object at the end of the queue.
void pop()Removes the first element of the queue.
void swap(queue & q) // C++11Swaps the content of the two queues.

Iterators

Because only the first and last element of a queue can be accessed (We can not iterate through a queue), iterators are useless with containers of type queue.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <queue> #include <iostream> int main() { std::queue<int> queue; // Inserts 10 numbers in the queue. for(unsigned c = 0; c < 10; c++) queue.push(c); std::cout << "The content of the queue of " << queue.size() << " elements:\n"; // As long as the queue is not empty. while(!queue .empty()) { // Prints the value of the first element of the queue. std::cout << queue.front() << ' '; // Takes off the first element of the queue. queue.pop(); } std::cout << '\n'; return 0; }