C++ Container Classes<queue>

In the C++ standard library<queue>The header file 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 rear) and removing elements at the other end (called the front).

A queue is a linear data structure that follows the following rules:

  • Elements can only be added from the back of the queue.
  • Elements can only be removed from the front of the queue.

Syntax

In C++, the syntax for a queue is as follows:

#include <queue>

// 声明队列
std::queue<Type> q;

HereTypeis 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(): Return a reference to the front element.
  • back(): Return a reference to the back element.
  • push(): Add an element to the back of the queue.
  • pop(): Remove the front element.

Example

Below is an example using the C++ standard library<queue>Simple example:

Example

#include <iostream>
#include <queue>

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 front element
    std::cout << "Front element: " << q.front() << std::endl;

    // Print the rear element
    std::cout << "Rear element: " << q.back() << std::endl;

    // Remove the front element
    q.pop();
    std::cout << "After removing the front element, front 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<queue>The standard library provides a convenient way to implement the queue data structure. By using queues, we can efficiently manage collections of elements that need to be processed in a specific order. Hopefully this article can help beginners better understand and use queues in C++.

Notes

  • A queue does not allow random access to elements, meaning elements in the queue cannot be accessed directly by index.
  • Queues are typically implemented using linked lists or dynamic arrays, depending on the specific implementation.
other extensions