51 lines
845 B
C++
51 lines
845 B
C++
|
|
#include <vector>
|
|
using namespace std;
|
|
|
|
template <class T>
|
|
class Heap
|
|
{
|
|
public:
|
|
typedef int (*Compare)(T& , T& );
|
|
|
|
private:
|
|
std::vector<T> data;
|
|
Compare compare;
|
|
|
|
public:
|
|
Heap()
|
|
{
|
|
}
|
|
|
|
Heap(Compare _compare)
|
|
{
|
|
this->compare = _compare;
|
|
}
|
|
|
|
~Heap()
|
|
{
|
|
}
|
|
|
|
|
|
|
|
void push(T value)
|
|
{
|
|
unsigned long cur_idx = this->data.size();
|
|
this->data.push_back(value);
|
|
|
|
for (;cur_idx != 0;)
|
|
{
|
|
unsigned long push_idx = (cur_idx - 1) >> 1;
|
|
T &push_value = this->data[push_idx];
|
|
if (this->compare(value, push_value) > 0)
|
|
{
|
|
this->data[cur_idx] = push_value;
|
|
cur_idx = push_idx;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
this->data[cur_idx] = value;
|
|
}
|
|
}; |