queue在STL中主要实现了先进先出(FIFO)的容器。
1.queue定义
#include<queue>
using namespace std;
queue < typename > q;
2.queue容器内元素的访问
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 );
}
printf( "%d\n%d\n", q.front (), q.back() );
return 0;
}
3.queue常用函数实例解析
push ()
q.push ( i ),将i进行入队。front (), back ()
分别获得队首元素和队尾元素。pop ()
令队首元素出队。
#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
queue < int > q;
for ( int i = 1; i <= 5; i++ ){
q.push ( i );
}
printf( "%d\n%d\n", q.front (), q.back() );
q.pop() ; //队首元素1出队
printf("%d\n", q.front() ); //输出为2
return 0;
}
empty ()
检测队列是否为空,空true 非空false
#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
queue < int > q;
if ( q.empty() == true )
printf("Empty!\n");
else
printf("Not empty!");
q.push(3);
if( q.empty() == true )
printf("Empty!");
else
printf("Not empty!");
return 0;
}
- size ()
返回queue内元素个数
#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
queue < int > q;
for ( int i = 1; i <= 5; i++ ){
q.push ( i );
}
printf("%d", q.size() ); //输出5
reutrn 0;
}