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;}
原创粉丝点击