c++ priority_queue

1、默认为大顶堆

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     priority_queue<int> p;
 8     int i;
 9     for (i = 0; i < 5; i++)
10         p.push(i);
11     for (i = 0; i < 5; i++)
12     {
13         cout << p.top() << " ";
14         p.pop();
15     }
16     return 0;
17 }

运行结果:

2、小顶堆

 1 int main()
 2 {
 3     priority_queue<int, vector<int>, greater<int>> p;
 4     //vs2013需要#include <functional>
 5     int i;
 6     for (i = 0; i < 5; i++)
 7         p.push(i);
 8     for (i = 0; i < 5; i++)
 9     {
10         cout << p.top() << " ";
11         p.pop();
12     }
13     return 0;
14 }

运行结果:

3、自定义

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 struct Node
 6 {
 7     int a, b;
 8     Node(int x, int y) : a(x), b(y) {}
 9 };
10 
11 struct cmp
12 {
13     bool operator() (Node *x, Node *y)
14     {
15         if (x->a != y->a) return x->a < y->a; //大顶堆
16         return x->b < y->b;
17     }
18 };
19 int main()
20 {
21 
22     priority_queue<Node *, vector<Node *>, cmp> p;
23     Node *n = new Node(1, 2); p.push(n);
24     n = new Node(1, 3); p.push(n);
25     n = new Node(2, 3); p.push(n);
26     while (!p.empty())
27     {
28         n = p.top();
29         p.pop();
30         cout << n->a << " " << n->b << endl;
31     }
32     return 0;
33 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/lxc1910/p/10225883.html
今日推荐