Action 1: Create a new priority queue:
PS: The operation needs to include the header file queue
Explain:
The next step is to explain the three parameters of the new one:
Where the first parameter is the data type of the priority queue, which can be int,double
The second parameter refers to what container is used to store this priority queue, which we generally use with vectors.
The third parameter is whether the priority queue root is a maximum or a minimum value, where greeter
Operation Two:
Insert an element:
t1.push(元素);t2.push(元素);
Operation Three:
View the elements at the top.
We use the top () function that comes with the priority queue to output the topmost element.
Let's say this:
printf ("%d\n", t1.top());printf ("%d\n", t2.top());
Operation Four:
Popup Top element:
t1.pop();t2.pop();
Operation Five: (Copy from)
If you want to customize the priority and the data type is not the base data type, but the complex data type, you must overload the operator ()
#include<iostream>#include<cstdio>#include<queue>using namespace std;typedef struct{ int a; int b;}Node;// 自定义优先级struct cmp{ bool operator()(const Node &t1,const Node &t2) { return t1.b<t2.b; // 相当于less,数据元素值大的优先级高 }};int main(){ int i,n; scanf("%d",&n); Node *num=new Node[n]; for(i=0;i<n;i++) { scanf("%d%d",&num[i].a,&num[i].b); } priority_queue<Node,vector<Node>,cmp> q(num,num+n); while(!q.empty()) { printf("%d ",q.top().b); q.pop(); } printf("\n"); return 0;}
Operation Five (copy):
The priority queue can also convert elements in a normal array to the initial value of a priority queue!
#include<iostream>#include<cstdio>#include<queue>using namespace std;int main(){ int a[6]={3,2,1,4,6,5}; priority_queue < int , vector <int> , less <int> > q (a,a+6); while(!q.empty()) { printf("%d ",q.top()); q.pop(); } printf("\n"); return 0;}
C + + STL priority queue