闲话少说,代码起步!!!
cpp
#pragma once
namespace cx
{
template<class T,class container=vector<T>, class Compare = less<T>>
class priority_queue
{
public:
void adjust_up(int child)
{
Compare com;
int parent = (child - 1) / 2;
while (child > 0)
{
if(com( _con[child], _con[parent]))
{
swap(_con[child], _con[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void adjust_down(int parent)
{
int child = parent * 2 + 1;
Compare com;
while (child< _con.size())
{
if (child + 1 < _con.size()&& com(_con[child + 1],_con[child]))
child++;
if (com(_con[child], _con[parent]))
{
swap(_con[parent], _con[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void push(const T& x)
{
_con.push_back(x);
adjust_up((int)size() - 1);
}
void pop()
{
swap(_con[0], _con[size() - 1]);
_con.pop_back();
adjust_down(0);
}
bool empty()
{
return _con.empty();
}
size_t size()const
{
return _con.size();
}
const T& top()
{
return _con[0];
}
void swap(T& a,T& b)
{
std::swap(a, b);
}
private:
container _con;
};
template<class T>
class greater
{
public:
bool operator()(const T& a, const T& b)
{
return a < b;
}
};
template<class T>
class less
{
public:
bool operator()(const T& a, const T& b)
{
return a > b;
}
};
}
希望大家可以参考可以实现自己的代码,感谢大家的阅读。