首页 > 文章列表 > C++ 函数的 STL queue 怎么用?

C++ 函数的 STL queue 怎么用?

Queue STL
465 2024-11-01

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

C++ 函数的 STL queue 怎么用?

如何使用 C++ STL Queue

简介

STL 的 queue 是一个先进先出(FIFO)容器。可以通过 std::queue 使用它,其中 T 表示元素类型。

特性

以下是一些 queue 的关键特性:

  • 先进先出: 首先插入的元素将首先删除。
  • 动态大小:队列可以在运行时自动调整大小。
  • 线程安全:在多线程应用程序中是线程安全的。

使用方法

以下是使用 STL queue 的步骤:

  1. 包括必需的头文件:
#include <queue>
  1. 声明队列:
std::queue<int> myQueue;
  1. 插入元素: 使用 push() 函数插入元素。
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
  1. 删除元素: 使用 pop() 函数删除元素。
myQueue.pop();
  1. 获取队列大小: 使用 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