C++:模拟实现一个优先级队列
1. 优先级队列介绍
- 优先级队列的底层结构使用的是堆
- 堆:将数据保存在一个数组中形成完全二叉树,如果该完全二叉树中任意节点的值都比其孩子节点大(小),则成为大(小)堆。
- 大(小)堆:堆顶元素是左右元素中最大(小)的
- 优先级队列(堆)的应用:堆排序、TOP-K问题
2. 优先级队列的使用
优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。注意:默认情况下priority_queue是大堆。
3. 模拟实现
模拟实现优先级队列实际上就是要模拟实现make_heap、push_heap、pop_heap这三个堆的接口函数,通过对堆元素的调整和对尾部元素的插入和删除实现优先级队列。
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vld.h>
#include<assert.h>
#include<vector>
using namespace std;
namespace bit
{
template<class T, class Cont = vector<T>, class Compare = less<T>>
class priority_queue
{
public:
priority_queue()
{}
template<class InputIterator>
priority_queue(InputIterator first, InputIterator last) :c(first, last)
{
int n = c.size();
int start = n / 2 - 1; //找到二叉树的最后一个分支
while (start >= 0)
{
_AdjustDown(start, n);
start--;
}
}
bool empty()const
{
if (c.size() > 0)
return false;
return true;
}
void push(const T& x)
{
c.push_back(x);
_AdjustUp(c.size() - 1);
}
void pop()
{
std::swap(c[0], c[c.size() - 1]);
c.pop_back();
_AdjustDown(0, c.size());
}
void show_heap()const
{
for (int i = 0; i < c.size(); ++i)
cout << c[i] << " ";
cout << endl;
}
protected:
void _AdjustDown(int start, int n)
{
int i = start;
int j = 2 * i + 1;
while (j < n)
{
//if(j+1<n && c[j]<c[j+1])
if (j + 1 < n && comp(c[j], c[j + 1]))
j++;
//if(c[i] < c[j])
if (comp(c[i], c[j]))
{
T tmp = c[i];
c[i] = c[j];
c[j] = tmp;
i = j;
j = 2 * i + 1;
}
else
break;
}
}
void _AdjustUp(int start)
{
int j = start;
int i = (j - 1) / 2;
while (i >= 0)
{
//if(c[j] > c[i])
if (comp(c[j], c[i]))
{
T tmp = c[i];
c[i] = c[j];
c[j] = tmp;
j = i;
i = (j - 1) / 2;
}
else
break;
}
}
private:
Cont c; //容器
Compare comp; //比较仿函数
};
};
void main()
{
vector<int> v{ 3,2,7,60,4,1,9,8,5 };
bit::priority_queue<int> pq(v.begin(), v.end());
pq.show_heap();
pq.push(15);
pq.show_heap();
pq.pop();
pq.show_heap();
cout << pq.empty() << endl;
system("pause");
}