cpp之priority_queue
- 大顶堆形式:priority_queue<int, vector
, less > - 小顶堆形式:priority_queue<int, vector
, greater >
代码演示
int main() {
int m;
cin >> m;
//小顶堆
priority_queue<int, vector<int>, greater<int>>q_greater;
//大顶堆
priority_queue<int, vector<int>, less<int>>q_less;
for (int i = 0; i < m; i++) {
int temp;
cin >> temp;
q_greater.push(temp);
q_less.push(temp);
}
cout << "greater is" << endl;
for (int i = 0; i < m; i++) {
cout << q_greater.top();
q_greater.pop();
}
cout << endl;
cout << "less is" << endl;
for (int i = 0; i < m; i++) {
cout << q_less.top();
q_less.pop();
}
return 0;
}
输出结果:
如果要自定义一个比较形式:
要重写一个结构体进行符号重载
class Node {
public:
int next[base] = { 0 };
int data;
bool operator () (Node* a,Node* b) {
return a->data > b->data;
}
};
class cmp {
public:
bool operator () (Node* a, Node* b) {
return a->data > b->data;
}
};
int main() {
int m;
cout << "输入个数" << endl;
cin >> m;
cout << "---" << endl;
priority_queue<Node*,vector<Node*>,cmp>q;
for (int i = 0; i < m; i++) {
int temp;
cin >> temp;
Node* n = new Node();
n->data = temp;
q.push(n);
}
cout << "greater is" << endl;
for (int i = 0; i < m; i++) {
cout << q.top()->data;
q.pop();
}
return 0;
}