C++优先队列(priority_queue)用法详解

优先级队列和普通队列相比,多了一个元素排序过程,而具体排序规则由传递函数参数决定

  • 头文件:
    #include

  • 基本函数
    empty()    如果队列为空,则返回真
    pop()    删除对顶元素,删除第一个元素
    push()    加入一个元素
    size()     返回优先队列中拥有的元素个数
    top()     返回优先队列对顶元素,返回优先队列中有最高优先级的元素

在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。

  • 定义:priority_queue即分别传入类型,容器类别,比较函数,这里比较函数可以自定义,也可以手写实现
  • 例子:
#include
#include
//升序队列
priority_queue ,greater > q;
//降序队列
priority_queue ,less >q;
#include
#include 
using namespace std;
int main() 
{
    priority_queue x; 
    //等同于 priority_queue, less > x;
    
    //             这里一定要有空格,不然成了右移运算符↓
    priority_queue, greater > y;  

    for (int i = 0; i < 5; i++) 
    {
        x.push(i);
        y.push(i);
    }
    while (!x.empty()) 
    {
        cout << x.top() << '  ';
        x.pop();
    } 
    cout << endl;

    while (!y.empty()) 
    {
        cout << y.top() << '  ';
        y.pop();
    }
    cout << endl;
system("pause");
    return 0;
}

结果:
4 3 2 1 0
0 1 2 3 4

你可能感兴趣的:(算法,C++)