You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <bits/stdc++.h>
using namespace std ;
/*
知识点内容: C++ STL 优先队列详解
优先队列是队列的一种,不过它可以按照自定义的一种方式(数据的优先级)来对队列中的数据进行动态的排序,
每次的push和pop操作, 队列都会动态的调整, 以达到我们预期的方式来存储。
例如, 将元素5 3 2 4 6依次push到优先队列中,
规定顺序为从大到小并输出, 输出顺序为6 5 4 3 2
文档内容参考:
https://www.cnblogs.com/aiguona/p/7200718.html
* */
struct node {
friend bool operator < ( node n1 , node n2 ) {
return n1 . priority < n2 . priority ;
}
int priority ;
int value ;
} ;
int main ( ) {
const int len = 5 ;
int i ;
int a [ len ] = { 3 , 5 , 9 , 6 , 2 } ;
//示例1: 从大到小输出
//priority_queue<int, vector<int>, less<int> > qi; //大顶堆
priority_queue < int > qi ; //简写版本
for ( i = 0 ; i < len ; i + + )
qi . push ( a [ i ] ) ;
for ( i = 0 ; i < len ; i + + ) {
cout < < qi . top ( ) < < " " ;
qi . pop ( ) ;
}
cout < < endl ;
//示例2: 从小到大输出
priority_queue < int , vector < int > , greater < int > > qi2 ; //小顶堆
for ( i = 0 ; i < len ; i + + )
qi2 . push ( a [ i ] ) ;
for ( i = 0 ; i < len ; i + + ) {
cout < < qi2 . top ( ) < < " " ;
qi2 . pop ( ) ;
}
cout < < endl ;
//示例3: 按优先级输出
priority_queue < node > qn ;
node b [ len ] ;
b [ 0 ] . priority = 6 ;
b [ 0 ] . value = 1 ;
b [ 1 ] . priority = 9 ;
b [ 1 ] . value = 5 ;
b [ 2 ] . priority = 2 ;
b [ 2 ] . value = 3 ;
b [ 3 ] . priority = 8 ;
b [ 3 ] . value = 2 ;
b [ 4 ] . priority = 1 ;
b [ 4 ] . value = 4 ;
for ( i = 0 ; i < len ; i + + )
qn . push ( b [ i ] ) ;
cout < < " 优先级 " < < ' \t ' < < " 值 " < < endl ;
for ( i = 0 ; i < len ; i + + ) {
cout < < qn . top ( ) . priority < < ' \t ' < < qn . top ( ) . value < < endl ;
qn . pop ( ) ;
}
return 0 ;
}