queue就是我们平常学的队列,STL集成了他的一些基本功能,很多函数,例如find(),erase(),等都与其他STL容器别无二致
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
int main()
{
//queue是先进先出队列,只能通过front访问首部,back访问尾部
//定义与其他STL容器别无二致
queue<int> q;
printf("push 1~5 to queue\n");
//push()用于将数据入队,下面把1,2,3,4,5依次入队
for(int i=1;i<=5;i++)
q.push(i);
//front()和back()可以分别访问队首队尾元素,O(1),返回值是队首队尾元素
int m=q.front();
cout<<"The m is q.front() = "<<m<<endl;
printf("output q.front(): %d and q.back(): %d\n",q.front(),q.back());
//pop()可以把队首元素出队,O(1)
for(int i=0;i<3;i++)
q.pop();
printf("pop three times from then the queue's q.front: %d\n",q.front());
//empty()检测queue是否为空,为空返回true,否则返回false,O(1)
//使用front()和pop()之前,必须要用empty来判空,否则会因为队空出现错误
printf("is queue empty?\n");
if(q.empty())
cout<<"Empty"<<endl;
else
cout<<"Not empty"<<endl;
printf("pop the last two number\n");
for(int i=0;i<2;i++)
q.pop();
if(q.empty())
cout<<"Empty"<<endl;
else
cout<<"Not empty"<<endl;
printf("push 1~7 to queue\n");
for(int i=1;i<=7;i++)
q.push(i);
//size()返回queue内的元素,O(1)
printf("q.size: %d\n",q.size());
return 0;
}