- C++ queue
- 前言
- 一、queue定义
- queue定义方式
- 二、queue常用函数
- 1.front():访问队首元素 与 back():访问队尾元素
- 2.pop():队首元素出队(删除队首元素)
- 3.empty():判断队列是否为空并返回结果,true 为空,false 为非空
- 4.size(): 获取队内元素个数
前言
queue 是一个实现了先进先出的容器(队列)。
一、queue定义如果要使用 queue, 需要先添加头文件,并加上 “using namespace std”
#includequeue定义方式using namespace std;
#include二、queue常用函数 1.front():访问队首元素 与 back():访问队尾元素using namespace std; queue Myqueue; //typename为任意数据类型或容器
因为 queue 就是数据结构中的队列, 所以在 STL 中只能访问其 队首元素 与 队尾元素,时间复杂度为 O(1)
示例如下:
#include#include using namespace std; queue MyQ; int main() { for(int i = 9; i > 4; i --) MyQ.push(i); //列表顺序应该为 9 8 7 6 5 cout << "队首" << MyQ.front() << endl; cout << "队尾" << MyQ.back() << endl; return 0; }
结果如下:
因为 queue 为数据结构中队列,所以元素只能从队首出队,时间复杂度为O(1)
代码如下(示例):
#include#include using namespace std; queue MyQ; int main() { for(int i = 10; i > 4; i --) MyQ.push(i); MyQ.pop(); cout << MyQ.front() << endl; return 0; }
结果如下:
时间复杂度O(1);
示例如下:
#include#include using namespace std; queue MyQ; int main() { for(int i = 1; i < 4; i ++) MyQ.push(i); cout << "push() 后的 empty() 值为" << MyQ.empty() << endl; for(int i = 0; i < 3; i ++) MyQ.pop(); cout << "pop() 后的 empty() 值为" << MyQ.empty() << endl; return 0; }
结果如下:
时间复杂度为O(1)
示例如下:
#include#include using namespace std; int main() { queue MyQ; for(int i = 1; i <= 5; i ++) MyQ.push(i); cout << "push() 后元素个数为:" << MyQ.size() << endl; return 0; }
结果如下:



