queue s是一种容器适配器,专门设计用于在FIFO上下文中操作(先进先出),其中元素插入容器的一端并从另一端提取。
queue s实现为容器适配器,它是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素被推入特定容器的“后面”并从其“前面” 弹出。
底层容器可以是标准容器类模板之一或其他一些专门设计的容器类。该底层容器应至少支持以下操作:
#include <queue> //队列头文件
queue <int> q; //定义队列
q.push(x);// 将 x 入队(首)
q.pop();// 删除队首元素
q.front();//返回最早入队元素
q.back();//返回最后入队元素
q.empty();//判断队列是否为空;空则返回true
q.size();//返回队列元素个数;
例:
1 #include <cstdio> 2 #include <iostream> 3 #include <queue> //头文件 4 //#define ISA_XR 5 using namespace std; 6 queue <int> q; //定义队列 7 int main() 8 { 9 #ifdef ISA_XR 10 freopen("Reverse_Polish_notation.in","r",stdin); 11 freopen("Reverse_Polish_notation.out","w",stdout); 12 #endif 13 int head,size,tail; 14 for(int i = 1;i <= 10;i++) 15 q.push(i); 16 /* 1~10入队 */ 17 if(!q.empty()) printf("Not empty\n"); 18 /* 判断队列是否为空,显然不空 */ 19 size = q.size(); 20 printf("The number of elements :%d\n",size); 21 /* 输出队中元素个数即队长 */ 22 tail = q.back(); 23 printf("The last element : %d\n",tail); 24 /* 输出队尾元素 */ 25 head = q.front(); 26 printf("The first element : %d\n",head); 27 /* 输出队首元素 */ 28 printf("The elements in the queue : "); 29 for(int i = 1;i <= size;i++) 30 { 31 head = q.front(); 32 printf("%d ",head); 33 q.pop(); 34 } 35 /* 输出每一个元素并删除队首元素 */ 36 cout<<endl; 37 if(q.empty()) printf("Empty now"); 38 /* 判断队列是否为空,空啦 */ 39 40 #ifdef ISA_XR 41 fclose(stdin); 42 fclose(stdout); 43 #endif 44 return 0; 45 }