什么是队列
队列原理
如果我们单说队列,大家可能没有详细的概念
我们可以联想一下生活中的排队买东西
后来的人要排在先来的人的后面
同样的道理,先来的人肯定会比后来的人先结束购物
也就会先出队
这就是队列的原理—先进先出
队列格式
在C++中,我们可以用这种方式定义一个队列:
queue<数据类型,容器类型>队列名;
数据类型即bool,int,char
等
容器类型如果不填则默认为 deque 类型
deque 即普通队列类型,先进先出
例如:
queue<int>q;
队列常用函数
函数格式 | 用法 |
---|---|
push(元素) | 在队列末尾加入一个元素 |
pop() | 删除队列首位元素 |
empty() | 如果队列为空则返回true,否则为false |
front() | 返回队列第一个元素 |
back() | 返回队列最后一个元素 |
size() | 返回队列的总元素个数 |
push_back(元素) | 强行插队,将元素插入队首 |
注:函数使用格式:队列名.函数
例:
q.empty();
示例:
- push()
#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
q.push(1);
q.push(2);
q.push(3);
//此时正序输出队列:1,2,3
return 0;
}
- pop()
#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
q.push(1);
q.push(2);
q.push(3);
q.pop();
//此时正序输出队列:2,3(1被删了)
return 0;
}
- empty()
#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
q.push(1);
q.pop();
cout<<q.empty(); //此时输出为true,队列内没有元素
return 0;
}
- front()
#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
q.push(1);
q.push(2);
cout<<q.front();//此时输出队列首位元素--1
return 0;
}
- back()
#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
q.push(1);
q.push(2);
cout<<q.back();//此时输出队列末尾元素--2
return 0;
}
- size()
#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
q.push(1);
q.push(2);
q.pop();
q.push(3);
cout<<q.size();//此时队列内元素数量:2
return 0;
}