#pragma once
#include<vector>
#include<iostream>
namespace crx {
using std::vector;
using std::cout;
using std::cin;
using std::endl;
//仿函数
template<class T>
struct less {
bool operator()(const T& a,const T& b) {
return a < b;
}
};
template<class T>
struct greater {
bool operator()(const T& a, const T& b) {
return a > b;
}
};
template<class T,class Container = vector<T>,class Compare = less<T>>
class priority_queue {
//默认是大堆,大的往上走
public:
void Swap(T& a,T& b) {
T p = a;
a = b;
b = p;
}
//向上调整算法
void AdjustUp(int child) {
int parent = (child - 1) / 2;
Compare com;
while (child > 0) {
//_con[child]>_con[parent]
if (com(_con[parent],_con[child])) {
Swap(_con[child], _con[parent]);
child = parent;
parent = (child - 1) / 2;
}
else {
break;
}
}
}
//向下调整算法
void AdjustDown(int root) {
int parent = root;
int child = parent * 2 + 1;
Compare com;
while (child < _con.size()) {
if (child + 1 < _con.size() && _con[child + 1] > _con[child]) {
child++;
}
//_con[parent] < _con[child]
if (com(_con[parent] , _con[child])) {
Swap(_con[parent], _con[child]);
parent = child;
child = 2 * parent + 1;
}
else {
break;
}
}
}
void push(const T& x)
{
_con.push_back(x);
AdjustUp(_con.size() - 1);
}
void pop()
{
Swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
AdjustDown(0);
}
T& top()
{
return _con[0];
}
size_t size()const
{
return _con.size();
}
bool empty()const
{
return _con.empty();
}
private:
Container _con;
};
void test_priority_queue() {
priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(9);
pq.push(4);
pq.push(2);
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
}
}
STL——priority_queue模拟
最新推荐文章于 2024-09-11 15:28:58 发布