优先队列用法
来源:互联网 发布:linux上telnet 编辑:程序博客网 时间:2024/06/01 13:04
优先队列用法
在优先队列中,优先级高的元素先出队列。
标准库默认使用元素类型的 <操作符 来确定它们之间的优先级关系。
//代码清单
#include<stdio.h>#include<queue>#include<iostream>using namespace std;int main( ){ priority_queue<int>q; //元素从大到小,默认的。 int t,i; for(i=1;i<=5;i++) { cin>>t; q.push(t); } while(!q.empty()) { cout<<q.top()<<" "; q.pop(); } return 0;}
#include<queue>#include<iostream>#include<algorithm>#include<functional>using namespace std;int main( ){ //priority_queue<int>q; //从小到大,需要传入一个比较函数,使用functional.h函数对像作为比较函数 //第二个参数为容器类型 ,greater比较函数 ,改为less后就为从大到小了。 priority_queue<int, vector<int>, greater<int> >q; int t,i; for(i=1;i<=5;i++) { cin>>t; q.push(t); } while(!q.empty()) { cout<<q.top()<<" "; q.pop(); } return 0;}
#include<queue>#include<iostream>#include<algorithm>#include<functional>using namespace std;struct node{ friend bool operator<(node a,node b) { return a.priority<b.priority; } int priority; int value;}; int main( ){ priority_queue<node>q; node b[5]; b[0].priority = 6; b[0].value = 1; b[1].priority = 9; b[1].value = 5; b[2].priority = 2; b[2].value = 3; b[3].priority = 8; b[3].value = 2; b[4].priority = 1; b[4].value = 4; int t,i; for(i=0;i<5;i++) { q.push(b[i]); } for(i=0;i<5;i++) { cout<<q.top().priority<<'\t'<<q.top().value<<endl; q.pop(); } return 0;}
第一种用法:
priority_queue<int> qi;
通过<操作符可知在整数中元素大的优先级高。
故示例1中输出结果为:9 6 5 3 2
第二种方法:
我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。
priority_queue<int, vector<int>, greater<int> >qi2;
其中:
第二个参数为容器类型。
第二个参数为比较函数。
故示例2中输出结果为:2 3 5 6 9
第三种方法:
自定义优先级。
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
在该结构中,value为值,priority为优先级。
通过自定义 operator< 操作符来比较元素中的优先级。
在示例3中输出结果为:
优先级 值
9 5
8 2
6 1
2 3
1 4
但如果结构定义如下:
struct node
{
friend bool operator> (node n1, node n2)
{
return n1.priority > n2.priority;
}
int priority;
int value;
};
{
friend bool operator> (node n1, node n2)
{
return n1.priority > n2.priority;
}
int priority;
int value;
};
则会编译不过(G++编译器)
因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系,而且自定义类型的 <操作符 与 >操作符 并无直接联系,故会编译不过。
0 0
- 优先队列的用法
- 优先队列的用法
- 优先队列用法
- 优先队列用法
- 优先队列的用法
- 优先队列用法
- 优先队列用法
- 优先队列用法
- C++ 优先队列用法
- 优先队列用法
- 优先队列用法
- C++ 优先队列用法
- 优先队列用法
- 优先队列用法
- 优先队列用法
- 优先队列的用法
- 优先队列的用法
- 优先队列用法
- 菜鸟的安卓实习之路----android广播(2)
- Runtime(三)
- 详解为QT Webkit编写插件案例实现
- 学习OpenGL简单总结
- [Leetcode] Rotate List
- 优先队列用法
- informatical lookup的使用详解
- Linux 大文件分割split与合并cat使用方法
- 关于手机设置中的RAM及内部存储空间
- 华侨大学总裁班管理分享:企业十二种最可怕的隐形成本
- Runtime(四)
- mongose链接数据库与批插入
- poj1270Following Orders(拓扑排序+dfs回溯)
- 【老李的模拟赛】【#4】【2014-08-09】