C++ 标准模板库(STL)中的 queue 是一个容器适配器,实现了先进先出(FIFO)的数据结构。以下是 queue 常用函数及其示例:
1. 头文件
#include <queue>
2. 常用函数
- push(const T& value) :将元素 value 入队,添加到队列的尾部。
- pop() :移除队列头部的元素,即最早入队的元素。
- front() :返回队列头部元素的引用(不删除元素)。
- back() :返回队列尾部元素的引用(不删除元素)。
- empty() :检查队列是否为空,若为空返回 true ,否则返回 false 。
- size() :返回队列中元素的个数。
3. 示例代码
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(10);
q.push(20);
q.push(30);
std::cout << "队头元素: " << q.front() << std::endl;
std::cout << "队尾元素: " << q.back() << std::endl;
std::cout << "队列元素个数: " << q.size() << std::endl;
std::cout << "队列是否为空: " << (q.empty()? "是" : "否") << std::endl;
q.pop();
std::cout << "出队一个元素后,队头元素: " << q.front() << std::endl;
return 0;
}