目录
仿函数
模拟实现
结果
大根堆
小根堆
完整代码
priority_queue.h
test.c
仿函数
仿函数的通俗定义:仿函数(functor)又称为函数对象(function object)是一个能行使函数功能
的类。仿函数的语法几乎和我们普通的函数调用一样,不过作为仿函数的类,都必须重operator()
运算符
模拟实现
结果
大根堆
小根堆
完整代码
priority_queue.h
#pragma once
template<class T,class Contianer=vector<T>,class Compare=Less<T>>
class priority_queue
{
public:
priority_queue()
{ }
void adjust_up(int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (com(_con[parent], _con[child]))
{
swap(_con[parent], _con[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void adjust_down(int parent)
{
int 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[parent], _con[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
template <class InputIterator>
priority_queue(InputIterator first, InputIterator last)
:_con(first, last)
{
for (int i = (_con.size() - 2) / 2; i >= 0; i--)
{
adjustup(i);
}
}
bool empty() const
{
return _con.empty();
}
size_t size() const
{
return _con.size();
}
const T& top()
{
return _con[0];
}
void push(const T& x)
{
_con.push_back(x);
adjust_up(_con.size() - 1);
}
void pop()
{
swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
adjust_down(0);
}
private:
Contianer _con;
Compare com;
};
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
using namespace std;
#include "priority_queue.h"
template<class T>
class Less
{
public:
bool operator()(const T& x, const T& y)
{
return x < y;
}
};
template<class T>
class Greater
{
public:
bool operator()(const T& x, const T& y)
{
return x > y;
}
};
void test()
{
priority_queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
while (!q.empty())
{
cout << q.top() << ' ';
q.pop();
}
cout << endl;
}
int main()
{
test();
return 0;
}