C++ priority_queue内元素优先级的设置以及注意事项
来源:互联网 发布:极限编程和瀑布模型 编辑:程序博客网 时间:2024/05/17 07:49
(1)基本数据类型的优先级设置
priority_queue< int> q;
priority_queue< int, vector< int>, less< int> > q;
一定要注意最后两个>之间有一个空格,否则编译时会报错 例如:error C2146: syntax error : missing ‘,’ before identifier ‘q’
这两种优先队列是等价的,less< int >表示数字大的优先级高,而greater正好相反
priority_queue< int, vector< int >, greater< int > > q;
(2) 结构体的优先级设置
struct House {
int number;// 楼栋号
int price; //价格每平米
};
如果你希望楼价高的优先级高,那么就需要重载小于号“<”
struct House {
int number;
int price;
friend bool operator < (House h1, House h2) {
return h1.price < h2.price;
}
};
如果希望价格低的优先级高,则
struct House {
int number;
int price;
friend bool operator < (House h1,House h2) {
return h1.price > h2.price;
}
};
还可以重写cmp函数
struct cmp {
bool operator () (House h1,House h2) {
return h1.price > h2.price;
}
};
priority_queue< House,vector< House>,cmp> q;//此处只是把greater<>部分替换成了cmp;
下面分享一个哈弗曼树求最小带权路径长度的用优先队列的实例:
//1 2 2 3 6为叶子结点#include<cstdio>#include<queue>using namespace std;//代表小顶堆的优先队列//priority_queue<long, vector<long>, greater<long> > q;int main() { priority_queue<int,vector<int>,greater<int> > q; int n; int temp,x,y, ans =0; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d",&temp); q.push(temp); //将初始值压入队列 } //printf("%d\n", ans); while(q.size() > 1) { //只要优先队列里面至少有两个元素 x = q.top(); q.pop(); y = q.top(); q.pop(); q.push(x + y); ans += x + y; } printf("%d\n", ans); //ans即为最小带权路径长度 return 0;}
- C++ priority_queue内元素优先级的设置以及注意事项
- 【day0414 C++】优先级队列 priority_queue的使用
- C++STL优先级队列priority_queue
- priority_queue 优先级队列的使用
- priority_queue 优先级队列的用法
- C语言运算符及优先级---以及注意事项(日积月累)
- c/c++优先级队列(priority_queue)
- css 的优先级以及设置css的优先级
- 纯 CSS实现根据元素已知的宽度设置高度以及注意事项
- STL中优先级队列的使用priority_queue
- STL中priority_queue的使用注意事项
- HTML元素的优先级
- 优先级队列priority_queue源代码
- STL - priority_queue 优先级队列
- priority_queue优先级队列
- priority_queue 优先级队列
- 优先级队列(priority_queue)
- 优先级队列priority_queue
- SecureCRT配色推荐和永久设置
- 深度学习简介
- RobotFrameWork(十)Remote远程库使用
- CycleGAN(以及DiscoGAN和DualGAN)简介
- leetcode 98. Validate Binary Search Tree DFS深度优先搜索 + 一个错误做法
- C++ priority_queue内元素优先级的设置以及注意事项
- hihoCoder1330—数组重排
- java8 接口之间继承与覆盖
- centos 6.5下安装、配置并启动SSH远程访问
- 最简单完全退出应用方式(活动依次出栈)
- bellman-Ford 算法(转)
- 提高组 模拟题训练
- jdbc连接到数据库
- Matlab——robotics toolbox