题目题解:http://blog.csdn.net/xu12110501127/article/details/9199335
有关博客:http://www.360doc.com/content/10/1118/16/963301_70454649.shtml 优先队列不错的博客。
priority_queue 对于基本类型的使用方法相对简单。
他的模板声明带有三个参数,priority_queue
Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
STL里面默认用的是 vector. 比较方式默认用 operator< ,
Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
STL里面默认用的是 vector. 比较方式默认用 operator< ,
所以如果你把后面俩个
参数 缺省的话,优先队列就是大顶堆,队头元素最大。
如果要用到小顶堆,则一般要把模板的三个参数都带进去。
STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆
例子:
1 #include <iostream>
2 #include <cstdio>
3 #include <queue>
4 #include <vector>
5 #include <algorithm>
6 #define LL long long
7 using namespace std;
8
9 struct node
10 {
11 int x, y;
12 bool operator < (const node &tmp)const
13 {
14 return x > tmp.x;
15 }
16 };
17 int main()
18 {
19 priority_queue<int>q1; //基本类型从大到小
20 priority_queue<int, vector<int>, greater<int> >q2; //基本类型从小到大
21 priority_queue<node>q3; //自定义类型
22 return 0;
23 }
示例:
1 struct node
2 {
3 int x, y;
4 bool operator < (const node &tmp)const
5 {
6 return x > tmp.x;
7 }
8 };
9
10 int main()
11 {
12 priority_queue<node>q; //定义
13 node no;
14 int n, i;
15 while(cin>>n)
16 {
17 for(i = 0; i < n; i++)
18 {
19 cin>>no.x>>no.y; //插入结构体
20 q.push(no);
21 }
22 while(n--)
23 {
24 cout<<(q.top()).x<<" "<<(q.top()).y<<endl; //输出
25 q.pop();
26 }
27 }
28 return 0;
29 }
原文链接: https://www.cnblogs.com/bfshm/p/3161694.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/93803
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!