# C++vector实现优先队列(大顶堆思想)

#include<iostream>
#include<vector>
using namespace std;

template<typename T>
class PriorityQueue{
private:
int size;	//the number of elements
const static int capacity = 100; 	//default capacity
vector<T> v;

int parent(int pos){return pos / 2;}
int l_child(int pos){return pos * 2;}
int r_child(int pos){return pos * 2 + 1;}

public:
PriorityQueue():size(0){v = vector<T>(capacity);}
bool isEmpty(){return size == 0;}
int get_size(){return size;}
bool en_queue(const T &t){
v[++size] = t;
for(int i = size;i > 1 && v[i] > v[parent(i)];i = parent(i)){
T temp = v[i];v[i] = v[parent(i)];v[parent(i)] = temp;
}
return true;
}
bool de_queue(T &max){
if(size < 1)	return false;
max = v[1];
v[1] = v[size];
v[size--] = max;
adjust(1);
return true;
}
void adjust(int pos){
int max_pos = pos;
if(r_child(pos) <= size)
max_pos = (v[l_child(pos)] > v[r_child(pos)]) ? l_child(pos) : r_child(pos);
else if(l_child(pos) <= size && v[l_child(pos)] > v[pos])
max_pos = l_child(pos);
if(max_pos != pos){
T temp = v[pos];v[pos] = v[max_pos];v[max_pos] = temp;
adjust(max_pos);
}
}

};

int main(){
PriorityQueue<int> p;
p.en_queue(8);
p.en_queue(4);
p.en_queue(5);
p.en_queue(1);
p.en_queue(9);
p.en_queue(15);
int i = -1;
while(p.de_queue(i)){
cout << i << " ";
}
return 0;
}