您的位置:首页 > 产品设计 > UI/UE

queue队列容器

2015-08-19 19:54 429 查看
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);

元素入队

入队函数为push,C++ 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: