C++实现priority_queue容器适配器
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现priority_queue容器适配器相关的知识,希望对你有一定的参考价值。
代码如下:
#pragma once
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
struct Less
{
bool operator()(const T &a, const T &b)
{
return a < b;
}
};
template<typename T>
struct Greater
{
bool operator()(const T &a, const T &b)
{
return a > b;
}
};
template<typename T, typename Container = vector<T>, typename Compare = Less<T>>
class priorityQueue
{
public:
void shiftDown()
{
int parent = 0;
int child = 2 * parent + 1;
while (child < con.size())
{
if (child + 1 < con.size() && cmp(con[child], con[child + 1]))
{
++child;
}
if (cmp(con[parent], con[child]))
{
swap(con[parent], con[child]);
parent = child;
child = 2 * parent + 1;
}
else break;
}
}
void shiftUp(int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (cmp(con[parent], con[child]))
{
swap(con[parent], con[child]);
child = parent;
parent = (child - 1) / 2;
}
else break;
}
}
void push(const T& val)
{
con.push_back(val);
shiftUp(con.size() - 1);
}
void pop()
{
swap(con[0], con[con.size() - 1]);
con.pop_back();
shiftDown();
}
T & top()
{
return con.front();
}
size_t size() const
{
return con.size();
}
bool empty() const
{
return con.empty();
}
private:
Container con;
Compare cmp;
};
测试代码如下:
#include <iostream>
#include "PriorityQueue.h";
using namespace std;
int main()
{
priorityQueue<int>pq;
pq.push(13);
pq.push(14);
pq.push(9);
pq.push(23);
pq.push(12);
pq.push(22);
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
priorityQueue<int, vector<int>, greater<int>> pq1;
pq1.push(13);
pq1.push(14);
pq1.push(9);
pq1.push(23);
pq1.push(12);
pq1.push(22);
while (!pq1.empty())
{
cout << pq1.top() << " ";
pq1.pop();
}
cout << endl;
class A
{
public:
A(int a = 1):_a(a){}
bool operator<(const A& a) const
{
return _a < a._a;
}
bool operator > (const A &a) const
{
return _a > a._a;
}
int _a;
};
priorityQueue<A> pq2;
pq2.push(A(123));
pq2.push(A(14));
pq2.push(A(13));
pq2.push(A(23));
pq2.push(A(88));
pq2.push(A(999));
while (!pq2.empty())
{
cout << pq2.top()._a << " ";
pq2.pop();
}
cout << endl;
return 0;
}
测试结果:
以上是关于C++实现priority_queue容器适配器的主要内容,如果未能解决你的问题,请参考以下文章
C++入门stack和queue适配器介绍+ priority_queue的模拟实现仿函数基本概念提及
C++初阶第十二篇—stack和queue(stack和queue的常见接口的用法与介绍+priority_queue+容器适配器+仿函数+模拟实现)