(1)queue和priority_queue的区别
- 普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。
- 在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。
(2)实现
优先队列具有队列的所有特性,包括队列的基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的。
<1>定义
priority_queue< type, container, function >
- Type 就是数据类型,
- Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),
- Functional 就是比较的方式。
当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。
<2>大顶堆和的小顶堆
//升序队列,小顶堆(因为是先进先出的,greater就是“>”)
priority_queue <int,vector<int>,greater<int> > q;
//降序队列,大顶堆
priority_queue <int,vector<int>,less<int> >q;
//这里一定要有空格,不然成了右移运算符
greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
less<int>和greater<int>,需要头文件:#include <functional>
(3)实例
<1>基本类型优先队列
//对于基础类型 默认是大顶堆
priority_queue<int> a;//等同于 priority_queue<int, vector<int>, less<int> > a;
//小顶堆
priority_queue<int, vector<int>, greater<int> > b;
for(int i=0;i<5;++i){
a.push(i);
b.push(i);
}
while (!a.empty()){
cout << a.top() << ' ';
a.pop();
}
cout << endl;
while (!c.empty()){
cout << c.top() << ' ';
c.pop();
}
- 运行结果:
4 3 2 1 0(大顶堆)
0 1 2 3 4(小顶堆)
<2>用pair做优先队列元素
规则:pair的比较,先比较第一个元素,第一个相等比较第二个。
priority_queue<pair<int, int> > a;
pair<int, int> b(1, 2);
pair<int, int> c(1, 3);
pair<int, int> d(2, 5);
a.push(d);
a.push(c);
a.push(b);
while (!a.empty())
{
cout << a.top().first << ' ' << a.top().second << '\n';
a.pop();
}
- 运行结果
2 3
1 5
1 2
<3>自定义类型做优先队列元素
//方法1
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();
}
}
- 运行结果
3 2 1
3 2 1
网友评论