The C++ container class
The C++ standard library's The header provides an implementation of the queue data structure. A queue is a First In First Out (FIFO) data structure that allows adding elements at one end (called the tail) and removing elements at the other end (called the head).
A queue is a linear data structure that follows these rules:
- Elements can only be added at the tail.
- Elements can only be removed at the head.
Syntax
In C++, the syntax of a queue is as follows:
#include
// Declare queue
std::queue q;
Here Type is the data type of the elements stored in the queue.
common operations
The queue provides the following common operations:
empty(): Check whether the queue is empty.size(): Return the number of elements in the queue.front(): Returns a reference to the head element.back(): Returns a reference to the tail element.push(): Add an element at the tail.pop(): Remove the head element.
Example
Here is a simple example using the C++ standard library :
Example
#include
#include
int
main
(
)
{
// Create an integer queue
std
::
queue
<
int
q;
// Add elements to the queue
q.
push
(
10
)
;
q.
push
(
20
)
;
q.
push
(
30
)
;
// Print the number of elements in the queue
std
::
cout
<<
"Number of elements in the queue: "
<<
q.
size
(
)
<<
std
::
endl
;
// Print the head element
std
::
cout
<<
"Head element: "
<<
q.
front
(
)
<<
std
::
endl
;
// Print the tail element
std
::
cout
<<
"Tail element: "
<<
q.
back
(
)
<<
std
::
endl
;
// Remove the head element
q.
pop
(
)
;
std
::
cout
<<
"After removing the head element, the head element: "
<<
q.
front
(
)
<<
std
::
endl
;
// Print the number of elements in the queue again
std
::
cout
<<
"Number of elements in the queue: "
<<
q.
size
(
)
<<
std
::
endl
;
return
0
;
}
Output result:
队列中的元素数量: 3
队首元素: 10
队尾元素: 30
移除队首元素后,队首元素: 20
队列中的元素数量: 2
C++'s standard library provides a convenient way to implement the queue data structure. By using a queue, we can effectively manage collections of elements that need to be processed in a specific order. I hope this article helps beginners better understand and use the queue in C++.
Notes
- A queue does not allow random access to elements, i.e., you cannot directly access elements in the queue by index.
- The implementation of a queue usually uses a linked list or a dynamic array, depending on the specific implementation.