priority_queue的模拟实现
priority_queue:
1 .优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的 。
2 .此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素) 。
3 .优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部 。
4 .底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
empty():检测容器是否为空
size():返回容器中有效元素个数
front():返回容器中第一个元素的引用
push_back():在容器尾部插入元素
pop_back(): 在容器尾部删除元素
5 .标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector 。
6 .需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作 。
#include<iostream>
#include<vector>
#include<list>
#include<deque>
using namespace std;
//模拟对于自定义Date类型,priority_queue接口的模拟实现及使用
template<class T, class Con = vector<T>, class Compare = Less<T>>
class Priority_queue
{
public:
void push(const T& x) {
_c.push_back(x);
shiftUp(_c.size() - 1);//最后一个孩子的位置
}
void pop() {
swap(_c[0], _c[_c.size() - 1]);
_c.pop_back();
shiftDown(0);//
}
T& top() {
return _c.front();
}
size_t size() const {
return _c.size();
}
bool empty()const {
return _c.empty();
}
private:
//向下调整,建大堆
void shiftDown(int parent) {
int child = 2 * parent + 1;
while (child < _c.size()) {
if (child + 1 < _c.size() && _com(_c[child], _c[child + 1]))
++child;
if (_com(_c[parent], _c[child])){
swap(_c[parent], _c[child]);
parent = child;
child = 2 * parent + 1;
}
else {
break;
}
}
}
//向上调整,建大堆
void shiftUp(int child) {
int parent = (child - 1) / 2;
while (child > 0) {
if (_com(_c[parent], _c[child])) {
swap(_c[child], _c[parent]);
child = parent;
parent = (child - 1) / 2;
}
else {
break;
}
}
}
private:
Con _c;
Compare _com;
};
//大于的仿函数
template <class T>
struct Greater
{
bool operator()(const T& a, const T& b) {
return a > b;
}
};
//小于的仿函数
template <class T>
struct Less
{
bool operator()(const T& a, const T& b) {
return a < b;
}
};
//自定义类型
class Date
{
public:
Date(int y,int m,int d)
:_y(y)
, _m(m)
, _d(d)
{}
//自定义类型判断大小得重载 > 和 < 运算符
bool operator>(const Date& d)const {
if (_y > d._y) {
return true;
}
else if(_y == d._y){
if (_m > d._m) {
return true;
}
else if (_m == d._m) {
if (_d > d._d) {
return true;
}
}
}
return false;
}
bool operator<(const Date& d)const {
if (_y < d._y) {
return true;
}
else if (_y == d._y) {
if (_m < d._m) {
return true;
}
else if (_m == d._m) {
if (_d < d._d) {
return true;
}
}
}
return false;
}
public:
int _y;
int _m;
int _d;
};
//<<对于自定义类型的重载
ostream& operator<<(ostream& cout, const Date& d){
cout << d._y << "-" << d._m << "-" << d._d << endl;
return cout;
}
void test1() {
Priority_queue<Date, vector<Date>, Greater<Date>> pr;
pr.push(Date(2011,2,2));
pr.push(Date(2012, 12, 2));
pr.push(Date(2011, 2, 1));
pr.push(Date(2015, 2, 22));
while (!pr.empty()) {
cout << pr.top() << endl;
pr.pop();
}
cout << endl;
}
int main() {
test1();
return 0;
}