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

如何使用 C++ STL Queue
简介
STL 的 queue 是一个先进先出(FIFO)容器。可以通过 std::queue 使用它,其中 T 表示元素类型。
立即学习“C++免费学习笔记(深入)”;
特性
以下是一些 queue 的关键特性:
使用方法
以下是使用 STL queue 的步骤:
#include <queue>
std::queue<int> myQueue;
push() 函数插入元素。myQueue.push(1); myQueue.push(2); myQueue.push(3);
pop() 函数删除元素。myQueue.pop();
size() 函数获取队列中的元素数。std::cout << "Queue size: " << myQueue.size() << std::endl;
实战案例
以下是一个使用 queue 的实战案例:
#include <queue>
int main() {
// 创建一个整数队列
std::queue<int> 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
以上就是C++ 函数的 STL queue 怎么用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号