C++STL优先级队列

C++STL优先级队列

优先级队列是特殊的队列,它与queue的区别在于它可以定义队列中数据的优先级,让优先级高的排在队列前面,可以优先出队,它本质上是由堆实现的。

定义

定义priority_queue<Type, Container, Functional>

  • Type:数据类型
  • Container:容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector)
  • Functional:比较的方式,当需要用自定义的数据类型时才需要传入第三个参数,使用基本数据类型时,只需要传入数据类型,其默认是大根堆
1
2
3
4
//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;

greaterless是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)。

基本操作

priority_queue的基本操作:

  • top 访问队头元素
  • empty 队列是否为空
  • size 返回队列内元素个数
  • push 插入元素到队尾 (并排序)
  • emplace 原地构造一个元素并插入队列
  • pop 弹出队头元素
  • swap 交换内容

使用实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main()
{
// pair 先比较first,first相等然后再比较second
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();
}
}

输出:

1
2
3
2 5
1 3
1 2

自定义类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <queue>
using namespace std;

//方法1
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator < (const tmp1& a) const
{
return x < a.x; // 大根堆
// return x > a.x // 小根堆
}
};

//方法2
struct tmp2 //重写仿函数
{
bool operator ()(tmp1 a, tmp1 b)
{
return a.x < b.x; // 大根堆
// 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(c);
f.push(b);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}

输出:

1
2
3
4
5
6
7
3
2
1
----
3
2
1

参考:c++优先队列(priority_queue)用法详解


C++STL优先级队列
https://gstarmin.github.io/2023/03/09/CppSTL优先级队列/
作者
Starmin
发布于
2023年3月9日
许可协议