C++ STL Queue

it2022-05-05  155

queue s是一种容器适配器,专门设计用于在FIFO上下文中操作(先进先出),其中元素插入容器的一端并从另一端提取。queue s实现为容器适配器,它是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素被推入特定容器的“后面”并从其“前面” 弹出。底层容器可以是标准容器类模板之一或其他一些专门设计的容器类。该底层容器应至少支持以下操作:

#include <queue> //队列头文件

queue <int> q; //定义队列

q.push(x);// 将 x 入队(首) q.pop();// 删除队首元素 q.front();//返回最早入队元素 q.back();//返回最后入队元素 q.empty();//判断队列是否为空;空则返回trueq.size();//返回队列元素个数;

 

例:

#include <cstdio>#include <iostream>#include <queue> //头文件 using namespace std;queue <int> q; //定义队列 int main(){ int head,size,tail; for(int i = 1;i <= 10;i++) q.push(i); /* 1~10入队 */ if(!q.empty()) printf("Not empty\n"); /* 判断队列是否为空,显然不空 */ size = q.size(); printf("The number of elements :%d\n",size); /* 输出队中元素个数即队长 */ tail = q.back(); printf("The last element : %d\n",tail); /* 输出队尾元素 */ head = q.front(); printf("The first element : %d\n",head); /* 输出队首元素 */ printf("The elements in the queue : "); for(int i = 1;i <= size;i++) { head = q.front(); printf("%d ",head); q.pop(); } /* 输出每一个元素并删除队首元素 */ cout<<endl; if(q.empty()) printf("Empty now"); /* 判断队列是否为空,空啦 */ return 0;}

转载于:https://www.cnblogs.com/xrisa/p/11203803.html


最新回复(0)