🔥个人主页:guoguoqiang. 🔥专栏:我与C++的爱恋
一、priority_queue的介绍和使用
优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部
底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
empty():检测容器是否为空
size():返回容器中有效元素个数
front():返回容器中第一个元素的引用
push_back():在容器尾部插入元素
pop_back():删除容器尾部元素
标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。
需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作
优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。注意:默认情况下priority_queue是大堆
构造函数
priority_queue pq;
创建一个优先级队列
empty()
检测优先级队列是否为空,是返回true,否则返回false
top()
返回栈顶元素(最大或者最小)
push()
在优先级队列中插入元素x
pop()
删除栈顶元素()
测试一下
#include <iostream>
#include <list>
#include <vector>
#include <queue>
using namespace std;
void test()
{
priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(5);
pq.push(4);
pq.push(2);
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
}
int main() {
test();
return 0;
}
默认情况下,priority_queue默认是大堆
仿函数的使用
class Container是内部存储队列中的容器类型
我们可以通过改变class compare来完成建立小堆,class Compare = less(大堆)
可以通过提供 std::greater 函数对象作为这个模板参数来改变为小堆
默认使用less这个仿函数,如果我们想要建立小堆,需要自己传一个参数
priority_queue<int,vector<int>,greater<int>> pq;
什么是仿函数呢?
在C++中,仿函数是一种使用对象来模拟函数的技术。他们通常是通过类实现的,该类重载了函数调用操作符(operator()),仿函数可以像普通函数一样被调用,但他们可以拥有状态。
#include <iostream>
using namespace std;
// 定义一个仿函数类
class Add {
public:
// 构造函数,可以用来初始化内部状态,这里没有使用
Add() {}
// 重载函数调用操作符
int operator()(int a, int b) {
return a + b;
}
};
int main() {
// 创建一个仿函数对象
Add add_func;
// 使用仿函数对象
cout << add_func(10, 3) << endl;
cout << add_func.operator()(1, 5) << endl;
cout << Add()(3, 5) << endl;
return 0;
}
仿函数广泛用于C++标准库中,特别是在算法(std::sort, std::for_each 等)中作为比较函数或者操作函数,以及在容器(如 std::set 或者 std::map)中作为排序准则
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Compare {
public:
bool operator()(int a, int b) {
return a < b; // 升序排列
}
};
int main() {
vector<int> v{ 2, 4, 1, 3, 5 };
// 使用仿函数对象
sort(v.begin(), v.end(), Compare());
for (int i : v) {
std::cout << i << " ";
}
// 输出:1 2 3 4 5
return 0;
}
greater和less
std::greater 和 std::less 是预定义的函数对象模板,用于执行比较操作。它们定义在头文件中。std::greater 用来执行大于(>)的比较,而 std::less 用来执行小于(<)的比较
#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v{ 5, 2, 4, 3, 1 };
// 使用 std::less 来升序排序
sort(v.begin(), v.end(), less<int>());
for (int i : v) {
cout << i << " ";// 1 2 3 4 5
}
cout << endl;
// 使用 std::greater 来降序排序
sort(v.begin(), v.end(), greater<int>());
for (int i : v) {
cout << i << " ";// 5 4 3 2 1
}
cout << endl;
return 0;
}
函数对象模板
#include <iostream>
using namespace std;
template<class T>
struct less {
bool operator()(const T& l, const T& r)const {
return l < r;
}
};
template<class T>
struct greater {
bool operator()(const T& l, const T& r)const {
return l < r;
}
};
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v{ 2, 4, 1, 3, 5 };
// 使用lambda表达式作为比较函数进行升序排列
sort(v.begin(), v.end(), [](int a, int b) { return a < b; });
for (int i : v) {
cout << i << " ";//1 2 3 4 5
}
cout << endl;
// 使用lambda表达式作为比较函数进行降序排列
sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
for (int i : v) {
cout << i << " ";//5 4 3 2 1
}
cout << endl;
return 0;
}
priority_queue<int,vector<int>,greater<int>> pq;
sort(v.begin(), v.end(), greater<int>());
priority_queue传的是一个类型,而sort需要传递对象,我们这里传递的是匿名对象
模拟实现
#pragma once
#include <vector>
namespace gwq {
template<class T>
class myless {
public:
bool operator()(const T& x, const T& y) {
return x < y;
}
};
template<class T>
class mygreater {
public:
bool operator()(const T& x, const T& y) {
return x > y;
}
};
template <class T, class Container = vector<T>, class compare = myless<T>>
class priority_queue {
public:
priority_queue() = default;
template<class InputIterator>
priority_queue(InputIterator first, InputIterator last) {
while (first != last) {
_con.push_back(*first);
++first;
}
for (int i = (_con.size() - 1 - 1) / 2; i >= 0; i--) {
adjust_down(i);
}
}
void adjust_up(int child) {
compare comfunc;
int parent = (child - 1) / 2;
while (child>0)
{
if (comfunc(_con[parent], _con[child]))
{
swap(_con[parent], _con[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void push(const T& x) {
_con.push_back(x);
adjust_up(_con.size() - 1);
}
void adjust_down(int parent) {
compare comfunc;
size_t child = parent * 2 + 1;
while (child < _con.size()) {
if (child + 1 < _con.size() && comfunc(_con[child], _con[child + 1])) {
++child;
}
if (comfunc(_con[parent], _con[child])) {
swap(_con[parent], _con[child]);
parent = child;
child = parent * 2 + 1;
}
else {
break;
}
}
}
void pop() {
swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
adjust_down(0);
}
const T& top() {
return _con[0];
}
size_t size() {
return _con.size();
}
bool empty() {
return _con.empty();
}
private:
Container _con;
};
}