Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The C++ container class

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:

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:

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