模拟实现priority_queue(优先级队列)
#pragma once
namespace shichun
{
template<class T>
struct less
{
bool operator()(const T& x, const T& y)const
{
return x < y;
}
};
template<class T>
struct greater
{
bool operator()(const T& x, const T& y)const
{
return x > y;
}
};
template<class T, class Container = vector<T>, class compare = greater<T>>
class priority_queue
{
private:
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;
}
}
public:
priority_queue()
{}
template<class InputIterator>
priority_queue(InputIterator first, InputIterator last)
:_con(first, last)
{
for (int i = (_con.size() - 1 - 1) / 2; i >= 0; i--)
{
adjust_down(i);
}
}
void Swap(T& a, T& b)
{
T tmp = a;
a = b;
b = tmp;
}
void push(const T& x)
{
_con.push_back(x);
adjust_up(size() - 1);
}
void pop()
{
Swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
adjust_down(0);
}
T& top()
{
return _con[0];
}
size_t size()
{
return _con.size();
}
bool empty()
{
return _con.empty();
}
private:
Container _con;
};
}