目录
一 . 优先级队列的使用
priority_queue - C++ Reference(优先级队列相关使用介绍)
实际上就是堆
包含的头文件 #include<queue>
相关使用:
二 . 优先级队列的模拟实现(部分的模拟实现)
先模拟实现没有仿函数参与优先级队列
template <class T, class Container = vector<T>>
class priority_queue
{
public:
priority_queue()
:c()
{ }
template <class InputIterator>
priority_queue(InputIterator first, InputIterator last)
: c(first, last)
{
for (int i = (c.size() - 2) / 2; i >= 0; i--)
{
adjust_down(i);
}
}
bool empty() //const
{
return c.empty();
}
size_t size() const
{
return c.size();
}
const T& top() const
{
return c[0];
}
void adjust_up(int child)//向上调整建堆
{
int parent = (child - 1) / 2;
while (child > 0)
{
if(c[parent] < c[child])
{
swap(c[parent], c[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void push(const T& x)
{
c.push_back(x);
adjust_up((int)c.size() - 1);
}
void adjust_down(int parent)//向下调整建堆
{
int child = 2 * parent + 1;
while (child < c.size())
{
if (child + 1 < c.size() && c[child] < c[child + 1]) child++;
if (c[parent] < c[child])
{
swap(c[child], c[parent]);
parent = child;
child = 2 * parent + 1;
}
else
{
break;
}
}
}
void pop()
{
swap(c[0], c[c.size() - 1]);
c.pop_back();
adjust_down(0);
}
private:
Container c;
//Compare com;
};
三 . 带上仿函数的模拟实现
1.仿函数介绍
2.模拟实现
template<class T>
struct Less
{
bool operator()(const T& a, const T& b)
{
return a < b;
}
};
template<class T>
struct Greater
{
bool operator()(const T& a, const T& b)
{
return a > b;
}
};
//Compare指的是Less<T>或者Greater<T>
template <class T, class Container = vector<T>, class Compare = Less<T> >
class priority_queue
{
public:
priority_queue()
:c()
{ }
template <class InputIterator>
//迭代器构造
priority_queue(InputIterator first, InputIterator last)
: c(first, last)
{
for (int i = (c.size() - 2) / 2; i >= 0; i--)
{
adjust_down(i);
}
}
bool empty() //const
{
return c.empty();
}
size_t size() const
{
return c.size();
}
const T& top() const
{
return c[0];
}
void adjust_up(int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
//if(c[parent] < c[child])
if (com(c[parent], c[child]))
{
swap(c[parent], c[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void push(const T& x)
{
c.push_back(x);
adjust_up((int)c.size() - 1);
}
void adjust_down(int parent)
{
int child = 2 * parent + 1;
while (child < c.size())
{
//if (child + 1 < c.size() && c[child] < c[child + 1]) child++;
if (child + 1 < c.size() && com(c[child], c[child + 1])) child++;
if (c[parent] < c[child])
{
swap(c[child], c[parent]);
parent = child;
child = 2 * parent + 1;
}
else
{
break;
}
}
}
void pop()
{
swap(c[0], c[c.size() - 1]);
c.pop_back();
adjust_down(0);
}
private:
Container c;
Compare com; //Compare指的是Less<T>或者Greater<T>
};