C++中的优先队列是 由二叉堆 实现的。 默认是使用 大根堆 实现。
优先队列的 基本操作 :
empty() 如果队列为空返回真
pop() 删除队顶元素
push() 入队一个元素
size() 返回优先队列中拥有的元素个数
top() 返回优先队列队顶元素
是默认的大根堆实现,top()是当前优先队列的最大值。
#include
#include
using namespace std;
int my_array[10] = {3,5,6,2,1,-8,10,4,-7,-6};
int main()
{
priority_queue q;
for (int i=0;i<10;i++)
{
q.push(my_array[i]);
}
for (int i = 0; i < 10; i++)
{
cout << "order: " << q.top() << endl;
q.pop();
}
}
执行结果是:
是 最小值的优先队列,top() 是当前优先队列的最小值。
#include
#include
using namespace std;
int my_array[10] = {3,5,6,2,1,-8,10,4,-7,-6};
int main()
{
priority_queue, greater> q;
for (int i=0;i<10;i++)
{
q.push(my_array[i]);
}
for (int i = 0; i < 10; i++)
{
cout << "order: " << q.top() << endl;
q.pop();
}
}
执行结果是:
是 最大值的优先队列,top() 是当前优先队列的最大值。
#include
#include
using namespace std;
int my_array[10] = {3,5,6,2,1,-8,10,4,-7,-6};
int main()
{
priority_queue, less> q;
for (int i=0;i<10;i++)
{
q.push(my_array[i]);
}
for (int i = 0; i < 10; i++)
{
cout << "order: " << q.top() << endl;
q.pop();
}
}
执行结果是: