堆heap 与 vector
namespace my_pqueue
{
template<class T, class Cont = vector<T>, class Compare = less<T>>
class priority_queue
{
public:
priority_queue() :c(){}
template<class InputIterator>
priority_queue(InputIterator first, InputIterator last) : c(first, last)
{
//手动将数组调整成堆, 形成堆
int n = c.size();
int start = n / 2 - 1;
while (start>=0)
{
_AdjustDown(start, n);
start--;
}
}
public:
void push(const T& x)
{
c.push_back(x);
_AdjustUp(c.size() - 1);
}
void pop()
{
std::swap(c[0], c[c.size() - 1]);
c.pop_back();
_AdjustDown(0, c.size());
}
bool empty() const
{
return c.empty();
}
size_t size() const
{
return c.size();
}
T& top() const
{
return c.front();
}
void show_heap()const
{
for (size_t i = 0; i < c.size(); ++i)
cout << c[i] << " ";
cout << endl;
}
protected:
void _AdjustDown(int start, int n)
{
int i = start;
int j = 2 * i + 1; //左子树
while (j < n)
{
//j+1为i节点的右子树,如果小于总节点数n,那么就存在右子树
/*if (j + 1< n && c[j]<c[j+1])*/
if (j + 1< n && comp(c[j], c[j + 1]))
j++;
//if (c[i] < c[j])
if (comp(c[i], c[j]))
{
T tmp = c[i];
c[i] = c[j];
c[j] = tmp;
i = j;
j = 2 * i + 1;
}
else
break;
}
}
void _AdjustUp(int start)
{
int j = start;
int i = (j - 1) / 2;
while (i >= 0)
{
//if (c[j] > c[i])
if (comp(c[j], c[i]))
{
T tmp = c[i];
c[i] = c[j];
c[j] = tmp;
j = i;
i = (j - 1) / 2;
}
else
break;
}
}
private:
Cont c;
Compare comp;
};
};