C++篇:队列queue的使用


基本操作:

push(x) 将x压入队列的末端

pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值

front() 返回第一个元素(队顶元素)

back() 返回最后被压入的元素(队尾元素)

empty() 当队列为空时,返回true

size() 返回队列的长度

使用方法:

头文件:

#include <queue>

声明方法: 
1、普通声明

queue<int> q;

2.结构体

struct node
{
    int x,y;
};
queue<node>   q;

#include <iostream>
#include <queue>
using namespace std; 
int main(){
queue<int> q; 
int s3=q.size();
printf("队列中当前元素个数:%d\n\n",s3);

for(int i=0;i<5;i++)
     q.push(i);
//q.push(1); //进队列
//q.push(2); //进队列
//q.push(3); //进队列
//q.pop(); //队首出队列
int s1=q.size();
printf("队列中当前元素个数:%d\n",s1);
int v1=q.front(); 
printf("队列中当前首元素:%d\n",v1);
int b1=q.back(); 
printf("队列中当前尾元素:%d\n\n",b1);


while(!q.empty()) 
    q.pop();   //重复使用时,初始化队列 

int s2=q.size();
printf("队列中当前元素个数:%d\n",s2);
int v2=q.front();
printf("队列中当前首元素:%d\n",v2);
int b2=q.back(); 
printf("队列中当前尾元素:%d\n\n",b2);

return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41297324/article/details/83186150
今日推荐