STL对我们说,准备好了priority给我们用♫

大根堆 :

priority_queue<int,vector<int>,less<int> >q;
或者简略写成 priority_queue<int>q;

小根堆:

priority_queue<int,vector<int>,greater<int> >q;

但是我们不满足,想要另辟蹊径♪

如何将自己定义的结构体作为 priority_queue 中的元素?
 
几种实现方法:
 
1.是他是他就是他,我们的好朋友:重载运算符~
//大根堆
struct Node {
int x;
Node(int x = 0) : x(x) {}
bool operator < (const Node &rhs) const {
return x < rhs.x;
}
};
priority_queue<Node, vector<Node>, less<Node> > q;

//小根堆
struct Node {
int x;
Node(int x = 0) : x(x) {}
bool operator > (const Node &rhs) const {
return x > rhs.x;
}
};
priority_queue<Node, vector<Node>, greater<Node> > q;
 

2.自己写比较类

//小根堆
struct Node {
int x;
Node(int x = 0) : x(x) {}
 };
struct cmp {
bool operator () (Node a, Node b) {  //可爱的括号运算符
return a.x > b.x;
 }
};
priority_queue<Node, vector<Node>, cmp> q;
满堂花醉三千客,一剑霜寒十四州
原文地址:https://www.cnblogs.com/phemiku/p/11619828.html