stl 的 queue 是一种先进先出的(fifo)容器,具有以下特性:先进先出、动态大小、线程安全。使用步骤包括:包含头文件、声明队列、插入元素(push())、删除元素(pop())、获取队列大小(size())。实战案例:创建一个整数队列,插入 5 个整数,遍历队列并打印元素。

如何使用 C++ STL Queue
简介
STL 的 queue 是一个先进先出(FIFO)容器。可以通过 std::queue 使用它,其中 T 表示元素类型。
立即学习“C++免费学习笔记(深入)”;
特性
以下是一些 queue 的关键特性:
- 先进先出: 首先插入的元素将首先删除。
- 动态大小:队列可以在运行时自动调整大小。
- 线程安全:在多线程应用程序中是线程安全的。
使用方法
以下是使用 STL queue 的步骤:
- 包括必需的头文件:
#include
- 声明队列:
std::queuemyQueue;
-
插入元素: 使用
push()函数插入元素。
myQueue.push(1); myQueue.push(2); myQueue.push(3);
-
删除元素: 使用
pop()函数删除元素。
myQueue.pop();
-
获取队列大小: 使用
size()函数获取队列中的元素数。
std::cout << "Queue size: " << myQueue.size() << std::endl;
实战案例
以下是一个使用 queue 的实战案例:
#includeint main() { // 创建一个整数队列 std::queue myQueue; // 插入 5 个整数 for (int i = 0; i < 5; i++) { myQueue.push(i); } // 遍历队列并打印元素 std::cout << "Elements in the queue: "; while (!myQueue.empty()) { std::cout << myQueue.front() << " "; myQueue.pop(); } std::cout << std::endl; return 0; }
输出:
Elements in the queue: 0 1 2 3 4










