优先队列
优先队列
核心代码
#pragma once
#include<iostream>
#include<vector>
#include<list>
using namespace std;
namespace mudan
{
//大堆
//Compare进行比较的仿函数 less -> 大堆 greater -> 小堆
template<class T, class Container = vector<T>,class Compare=std::less<T>>
class priority_queue
{
public:
priority_queue()
{}
template<class InputIterator>
priority_queue(InputIterator first, InputIterator last)
{
while (first != last)
{
_con.push_back(*first);
first++;
}
for (int i = (_con.size() - 1 - 1) / 2; i >= 0; i--)
{
Adjust_down(i);
}
}
size_t size()
{
return _con.size();
}
void Adjust_up(size_t child)
{
Compare compare;
size_t parent = (child - 1) / 2;
while (child>0)
{
if (compare(_con[parent],_con[child]))
{
std::swap(_con[parent], _con[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void Adjust_down(size_t parent)
{
Compare com;
size_t child = parent * 2 + 1;
while (child < _con.size())
{
// 选出左右孩子中大的那一个
//if (child+1 < _con.size() && _con[child+1] > _con[child])
//if (child + 1 < _con.size() && _con[child] < _con[child + 1])
if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
{
++child;
}
//if (_con[child] > _con[parent])
//if (_con[parent] < _con[child])
if (com(_con[parent], _con[child]))
{
std::swap(_con[child], _con[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void push(const T& val)
{
_con.push_back(val);
Adjust_up(_con.size()-1);//调堆
}
void pop()
{
std::swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
Adjust_down(0);
}
const T& top()const
{
return _con[0];
}
bool empty()
{
return (_con.size() == 0);
}
bool empty() const
{
return (_con.size()==0);
}
private:
Container _con;//容器
};
void test()
{
priority_queue<int,vector<int>,greater<int>>pq;
pq.push(1);
pq.push(2);
pq.push(3);
pq.push(4);
pq.push(6);
pq.push(6);
pq.push(5);
pq.push(6);
while (!pq.empty())
{
cout << pq.top()<<" ";
pq.pop();
}
cout << endl;
int arr[] = { 9,2,5,7,1,8,2,3,6,7,8,9,12,15,19,21 };
priority_queue<int,vector<int>,greater<int>>p(arr, arr + sizeof(arr) / sizeof(arr[0]));
while (!p.empty())
{
cout << p.top() << " ";
p.pop();
}
}
}