//关于priority_queue的使用:
/* 默认情况下使用less<int>即大顶堆(由大到小排序),当使用greater<int>即小顶堆(由小到大排序)
定义: priority_queue<Type, Container, Functional>
Type: 数据类型
Container: 容器类型(Container必须是用数组实现的容器,比如vector、deque等等STL里面默认用的是vector)
Functional: 比较的方式(默认less<int>)
当需要用自定义的数据类型时才需要传入这三个参数;使用基本数据类型时,只需要传入数据类型.
*/
#include <iostream>
#include <queue>
using namespace std;
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const
{
return x < a.x; //大顶堆
}
};
//方法2
struct tmp2 //重写仿函数
{
bool operator() (tmp1 a, tmp1 b)
{
return a.x < b.x; //大顶堆
}
};
int main()
{
tmp1 a(1);
tmp1 b(2);
tmp1 c(3);
priority_queue<tmp1> d;
d.push(b);
d.push(c);
d.push(a);
while (!d.empty())
{
cout << d.top().x << '\n';
d.pop();
}
cout << endl;
priority_queue<tmp1, vector<tmp1>, tmp2> f;
f.push(b);
f.push(c);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}
priority_queue介绍
最新推荐文章于 2022-08-18 10:55:22 发布