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 ;
}