queue常用用法
queue翻译为队列主要实现的是一个先进先出的容器
1.queue的定义
要添加头文件并且加上using namespace std
定义方法与其他写法基本相同
queue<int> q;
2.queue的元素访问
因为是先进先出的限制性的数据结构,所以只可通过front()和back()来访问队首和队尾元素
例如:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout<<q.front()<<' ';
cout<<q.back()<<endl;
return 0;
}
//输出结果为 1 4
3.queue常用函数的解析
(1)push()
push(x)将x元素入队,时间复杂度为O(1)上面的例子提到过。
(2)front()和back()
访问队首元素和队尾元素时间复杂度为O(1)。
(3)pop()
pop()指将队首元素移除队列时间复杂度为O(1)。
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout<<q.front()<<' ';
q.pop();
cout<<q.front()<<' ';
//输出结果为 1 2
(4)empty()
检测queue队列是否为空
空则返回true,非空则返回false
时间复杂度为O(1)
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
if(q.empty())
cout<<"empty"<<endl;
else
cout<<"not_empty"<<endl;
q.pop();
if(q.empty())
cout<<"empty"<<endl;
else
cout<<"not_empty"<<endl;
}
/*
输出结果为
not_empty
empty
*/
(5)size()
size()返回queue的元素个数,时间复杂度为O(1)
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout<<q.size()<<endl;
}
/*
输出结果为
4
*/
queue的常见用途
实现bfs时会需要实现一个队列,用queue可以提高程序的准确性
另外要注意使用front()和pop()之前最好要使用empty()判断队列非空
这里就有一篇关于使用queue作为队列实现bfs的
学霸迷宫可以参考一下具体使用方法