C++标准库模板

priority_queue的成员函数:

1 top()             // 访问队头元素
2 empty()        // 队列是否为空
3 size()           // 返回队列内元素个数
4 push()         // 插入元素到队尾 (并排序)
5 emplace()    // 原地构造一个元素并插入队列
6 pop()          // 弹出队头元素
7 swap()        //  交换内容   

两种写法:

下面两种优先队列的定义是等价的(以int型为例),都是大顶堆
priority_queue<int>q;
priority_queue<int,vector<int> , less<int> >q;(把元素最小的元素放在队首)

 

定义priority_queue<Type, Container, Functional>
Type 就是数据类型

Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector)

Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆

     如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。

     这里自定义数据类型的比较方式要使用自定义的仿函数

两种排列方式:

1 priority_queue<Node,vector<Node>,less<Node>> p1 //大顶堆
2 priority_queue<Node,vector<Node>,greater<Node>> p2//小顶堆

上面的less和greater是std实现的两个仿函数,基本数据类型可以直接使用,自定义数据类型需要自定义

 

用小于比较时,最右侧是最大元素,大顶堆

用大于比较时,最右侧是最下元素,小顶堆

 

基本数据类型的例子:

 1 #include<iostream>
 2 #include <queue>
 3 using namespace std;
 4 int main() 
 5 {
 6     //对于基础类型 默认是大顶堆
 7     priority_queue<int> a; 
 8     //等同于 priority_queue<int, vector<int>, less<int> > a;
 9     
10     //             这里一定要有空格,不然成了右移运算符↓
11     priority_queue<int, vector<int>, greater<int> > c;  //这样就是小顶堆
12     priority_queue<string> b;
13 
14     for (int i = 0; i < 5; i++) 
15     {
16         a.push(i);
17         c.push(i);
18     }
19     while (!a.empty()) 
20     {
21         cout << a.top() << ' ';
22         a.pop();
23     } 
24     cout << endl;
25 
26     while (!c.empty()) 
27     {
28         cout << c.top() << ' ';
29         c.pop();
30     }
31     cout << endl;
32 
33     b.push("abc");
34     b.push("abcd");
35     b.push("cbd");
36     while (!b.empty()) 
37     {
38         cout << b.top() << ' ';
39         b.pop();
40     } 
41     cout << endl;
42     return 0;
43 }

输出:

1 4 3 2 1 0
2 0 1 2 3 4
3 cbd abcd abc

 

对于pair,pari的比较,先比较第一个元素,第一个相等比较第二个

 

自定义数据类型的例子:

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 //方法1
 6 struct tmp1 //运算符重载<
 7 {
 8     int x;
 9     tmp1(int a) {x = a;}
10     bool operator<(const tmp1& a) const
11     {
12         return x < a.x; //大顶堆
13     }
14 };
15 
16 //方法2
17 struct tmp2 //重写仿函数
18 {
19     bool operator() (tmp1 a, tmp1 b) 
20     {
21         return a.x < b.x; //大顶堆
22     }
23 };
24 
25 int main() 
26 {
27     tmp1 a(1);
28     tmp1 b(2);
29     tmp1 c(3);
30     priority_queue<tmp1> d;
31     d.push(b);
32     d.push(c);
33     d.push(a);
34     while (!d.empty()) 
35     {
36         cout << d.top().x << '\n';
37         d.pop();
38     }
39     cout << endl;
40 
41     priority_queue<tmp1, vector<tmp1>, tmp2> f;
42     f.push(c);
43     f.push(b);
44     f.push(a);
45     while (!f.empty()) 
46     {
47         cout << f.top().x << '\n';
48         f.pop();
49     }
50 }

输出:

1 3
2 2
3 1
4 
5 3
6 2
7 1

 

posted on 2020-09-14 15:51  高数考了59  阅读(120)  评论(0)    收藏  举报