table of Contents
Queue translates to queues. In STL, it mainly implements a first-in first-out container.
Definition of queue
To use queue, you should add the header file first:
#include<queue>
Other things needed:
using namespace std;
Its definition is written in the same way as other STL containers, and typename can be any basic data type or container:
queue<typename> name;
Access to elements in the queue container
Because the queue itself is a first-in, first-out restrictive data structure,
in STL, only front() can be used to access the head element or back() to access the tail element.
Queue commonly used functions
(1) push()
push(x ) enqueues x into the queue, and the time complexity is O(1).
(2) front(), back()
front() and back() can obtain the head and tail elements of the team respectively, and the time complexity is O(1).
(3) pop()
pop() makes the first element of the team go out of the team, and the time complexity is O(1).
(4) empty()
empty() detects whether the queue is empty, returns true if it is empty, and returns false if it is not empty. The time complexity is O(1).
(5) size()
size() returns the number of elements in the queue, and the time complexity is O(1).
Common uses of queue
When you need to implement breadth-first search, you don't need to manually implement a queue yourself, but instead use queue to improve the accuracy of the program.
Another point to note is that before using the front() and pop() functions, you must use empty() to determine whether the queue is empty, otherwise an error may occur because the queue is empty .
Extension: There are two types of containers in STL that are related to queues, namely deque and priority_queue. The
former is a queue that can be inserted and deleted from the beginning and the end, and the latter is the default implementation using the heap. The largest element of the current queue is placed at the top of the queue.