queue的定义
queue:队列,实现了一个先进先出的容器,需添加头文件#include
queue name;
queue容器内元素的访问
由于队列本身就是一种先进先出的限制性数据结构,只能通过front()来访问队首元素,或者是通过back()来访问队尾元素。
#include <stdio.h>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
for(int i = 1; i <= 5; i++)
{
q.push(i); // push(i)用以将i压入队列,因此依次入队1 2 3 4 5
}
printf("%d %d\n", q.front(), q.back()); // 输出结果是1 5
return 0;
}
1 5
queue常用函数实例
(1) push()
push(x):将x进行入队,时间复杂度为O(1)。
(2) front()、back()
front()和back()可以分别获得队首元素和队尾元素,时间复杂度为O(1)。
(3) pop()
pop():令队首元素出队,时间复杂度为O(1)。
#include <stdio.h>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
for(int i = 1; i <= 5; i++)
{
q.push(i); // push(i)用以将i压入队列,因此依次入队1 2 3 4 5
}
for(int i = 1; i <= 3; i++)
{
q.pop(); //出队首元素三次(即依次出队1 2 3)
}
printf("%d\n", q.front());
return 0;
}
4
(4)empty()
empty():检测queue是否为空,返回true则空,返回false则非空,时间复杂度为O(1)。
#include <stdio.h>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
if(q.empty() == true) // 一开始队列内没有元素,所以为空
{
printf("Empty\n");
}
else
{
printf("Not Empty\n");
}
q.push(1);
if(q.empty() == true) //在入队“1”后,队列非空
{
printf("Empty\n");
}
else
{
printf("Not Empty\n");
}
return 0;
}
Empty
Not Empty
(5)size()
size():返回queue内元素的个数,时间复杂度为O(1)。
#include <stdio.h>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
for(int i = 1; i <= 5; i++)
{
q.push(i); // push(i)用以将i压入队列
}
printf("%d\n", q.size()); // 队列中有5个元素
return 0;
}
5
queue的常见用途
当需要实现广度优先搜索时,可以不用自己手动实现一个队列,而是用queue作为代替,以提高程序的准确性。
另外有一点注意,使用front()和pop()函数前,必须用empty()判断队列是否为空,否则可能因为队空而出现错误。