queue队列容器

queue队列也是一种线性存储表,元素的插入在表的一端进行,在表的另一端删除,具有先进先出的特点,插入的一端称为队尾,删除的一端称为队首。C++ STL的队列泛化,默认使用双端队列容器deque作为底层架构。元素的出队不返回队首元素,需要调用取队首函数来获取队首元素。队列是一种常用的数据结构,通常以消息队列的形式应用于进程间通信。

创建queue对象

有以下两种方式。

(1)    queue()

queue<int> q;

(2)    queue(const queue&)

queue<int,list<int> > q1;

queue<int,list<int> > q2(q1);

元素入队

入队函数为pushC++ STL没有预先设定队列的大小,元素入队不会判断是否队满。

queue<int> q;

q.push(1);

q.push(2);

q.push(3);

元素出队

出队函数pop,函数不会判断队列是否为空,需要自行判断。

queue<int> q;

while(!q.empty())

{

         q.pop();

}

取队首、队尾元素

队列容器的front函数和back函数,分别读取队首和队尾元素。

queue<int> q;

while(!q.empty())

{

         cout<<q.front()<<endl;

         q.pop();

}

 

非空判断,调用empty函数。

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	queue<int> q;
	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);
	q.push(5);
	while(!q.empty())
	{
		cout<<q.front()<<endl;//1、2、3、4、5
		q.pop();
	}
	return 0;
}

size函数获取队列的大小。

#include<iostream>
#include<queue>
#include<list>
#define QUEUE_SIZE 2
using namespace std;
int main()
{
	queue<int,list<int> >q;
	if(q.size()<QUEUE_SIZE)
	{
		q.push(1);
	}
	if(q.size()<QUEUE_SIZE)
	{
		q.push(10);
	}
	if(q.size()<QUEUE_SIZE)
	{
		q.push(15);
	}
	while(!q.empty())
	{
		cout<<q.front()<<endl;//1、10 
		q.pop(); 
	}
	return 0;
}


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值