一、priority_queue是什么
priority_queue 是容器适配器,它提供常数时间的(默认)最大元素查找,对数代价的插入与释出。
可用用户 提供的 Compare
更改顺序,例如,用 std::greater<T> 将导致最小元素作为 top() 出现。
用 priority_queue
工作类似管理某些随机访问容器中的堆,优势是不可能突然把堆非法化。
二、使用
priority_queue实际就是把优先级最高的一个数据放在最前面(大/小堆)。
#include<queue>
#include<iostream>
using namespace std;
void test_pq()
{
vector<int> v = { 0,8,7,1,9 };
priority_queue<int> q(v.begin(), v.end());
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
while (!q.empty())
{
cout << q.top() << endl;
q.pop();
}
}
int main()
{
test_pq();
return 0;
}
三、模拟实现
#include<iostream>
#include<vector>
#include<functional>
namespace gu
{
template <class T, class Container = vector<T>, class Compare = less<T> >
class priority_queue
{
public:
priority_queue()
{
}
template <class InputIterator>
priority_queue(InputIterator first, InputIterator last)
:c(first,last)
{
for (int i = (c.size() - 2) / 2; i >= 0; i--)
{
adjust_down(i);
}
}
bool empty() const
{
return c.empty();
}
size_t size() const
{
return c.size();
}
const T& top()
{
return c[0];
}
void adjust_down(int parent)
{
size_t child = parent * 2 + 1;
while (child < c.size())
{
if (child + 1 < c.size() && comp(c[child ] , c[child + 1]))
{
child++;
}
if (comp(c[parent], c[child]))
{
swap(c[parent], c[child]);
parent = child;
child = child * 2 + 1;
}
else
{
break;
}
}
}
void adjust_up(int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (comp(c[parent], c[child]))
{
swap(c[child], c[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void push(const T& x)
{
c.push_back(x);
adjust_up(c.size() - 1);
}
void pop()
{
swap(c[0], c[c.size() - 1]);
c.pop_back();
adjust_down(0);
}
private:
Container c;
Compare comp;
};
};