queue
翻译为队列,主要是实现一个先进先出的容器,因此只能访问队列的首尾两个元素。
引用头文件
#include <queue>
初始化赋值
queue<int> que; // 初始化空队列
auto it = {1, 2, 3, 4, 5};
queue<int> q(it);
遍历 queue 容器
队列中的数据和堆栈一样是不允许随机访问的,即不能通过下标访问,且队列内的元素也是无法遍历的。
迭代器
无
queue 常用方法
方法 | 说明 |
---|---|
back() | 返回队列中最后一个元素 |
empty() | 判断队列是否为空 |
front() | 返回队列中的第一个元素 |
pop() | 删除队列的第一个元素 |
push(val) | 在队列末尾加入一个元素 |
size() | 返回队列中元素的个数 |
入队 push
vector<int> v = {1, 2, 3, 4};
queue<int> que;
for(int x : v) {
que.push(x);
}
出队 pop
vector<int> v = {1, 2, 3, 4};
queue<int> que;
for(int x : v) {
que.push(x);
}
for(int i = 0; i < 2; i++) {
que.pop();
}