首页 > 其他 > 详细

STL 队列

时间:2014-02-22 09:23:16      阅读:533      评论:0      收藏:0      [点我收藏+]

queue(队列)数据结构的基础,一种特殊的线性表,队列就像排队打饭一样先排的先打,后排的后打;只能从前面出,从后面进;

queue<int> q ;

q.pop() 删除第一个元素

q.push( x ) 将 x 添加到最后

q.front()   访问第一个元素

q.back() 访问最后一个元素

q.empty() 判断队列是否为空

q.size() 判断队列中元素的个数

在普通队列的基础上,还定义了一种优先队列(priority_queue),在优先队列中,优先级别越高的数据,优先出队。

默认优先级为从大到小。

例如:

#include<iostream>
#include<queue>

using namespace std ;

int main()	{
	priority_queue<int> q ;
	int a[] = { 2 , 1 , 4 , 3 , 7 , 5 , 6 } ;
	for( int i = 0 ; i < 7 ; i++ )
		q.push( a[i] ) ;
	while( !q.empty() )	{
		cout << q.top() << " " ;
		q.pop();
	}
	cout<<endl;
	return 0 ;
}
输出:7 6 5 4 3 2 1 ;

如何使得输出成为从小到大?

这时我们可以自定义优先级:

#include<iostream>
#include<queue>

using namespace std ;

struct node	{
	int priority ;
	int value ;
	friend bool operator<( node n1 , node n2 )	{
		return n1.priority < n2.priority ;
	}
} ;

int main()	{
	priority_queue<node> q ;
	node c[7] ;
	int a[] = { 2 , 1 , 4 , 3 , 7 , 5 , 6 } ;
	int b[] = { 9 , 8 , 7 , 6 , 4 , 5 , 3 } ;
	for( int i = 0 ; i < 7 ; i++ )	{
		c[i].priority = b[i] ;
		c[i].value = a[i] ;
	}
	for( int j = 0 ; j < 7 ; j++ )	
		q.push(c[j]) ;
	while( !q.empty() )	{
		cout << q.top().value << " " ;
		q.pop();
	}
	cout<<endl;
	return 0 ;
}


STL 队列

原文:http://blog.csdn.net/ding_hai_long/article/details/19611345

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!