查询文献,根据其属性进行模拟实现
//容器默认为vertor,排序方式默认使用仿函数less
template<class T,class Container=vector<T>,class Compare=less<T>>
class priority_queue
{
public:
void adjust_up(size_t child)
{
//向上调整
Compare com;
//堆里面孩子父亲的计算公式
size_t parent = (child - 1) / 2;
while (child > 0)
{
if (com(_con[parent],_con[child]))
{
swap(_con[child], _con[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
break;
}
}
void adjust_down(size_t parent)
{
Compare com;
size_t child = parent * 2 + 1;
while (child < _con.size())
{
//判断右孩子是否存在并与左孩子比较大小
if (child + 1 < _con.size() && com(_con[child],_con[child+1]))
child++;
if (com(_con[parent],_con[child]))
{
swap(_con[child], _con[parent]);
parent = child;
child = parent * 2 + 1;
}
else
break;
}
}
void push(const T& x)
{
//插入后向上调整继续保证堆的结构
_con.push_back(x);
adjust_up(_con.size()-1);
}
void pop()
{
//将最大值与最尾互换删除
swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
//向下调整
adjust_down(0);
}
const T& top()
{
return _con[0];
}
bool empty()
{
return _con.empty();
}
private:
Container _con;
};