C++ 优先队列priority_queue

C++ 优先队列priority_queue

参考博客

优先队列

  • 优先级队列是一个拥有权值观念的queue。它允许在底端添加元素、在顶端去除元素、删除元素。
  • 缺省情况下,优先级队列利用一个大顶堆完成。STL堆详解与编程实现

头文件&定义

#include <queue>
#include <functional> //greater<>

// 定义
priority_queue<int> pq;

默认优先输出大数据

  • priority_queue<Type, Container, Functional>

  • 其中, Type 为数据类型. Container 为保存数据的容器. Functional 为元素比较的方式.

  • 若不写后面两个参数.

    容器 默认使用 vector

    比较方式 默认使用 operator < 即优先队列是大顶堆. 队头元素最大.

举例

srand(time(NULL));
priority_queue<int> pq1; // 默认是最大堆...
std::cout << "start..." << endl;
for (int i = 0; i < 10; i++) {
    int t = rand() % 100;
    cout << t << ends;
    pq1.push(t);
}
std::cout << endl;
while (!pq1.empty())
{
    cout << pq1.top() << ends;
    pq1.pop();
}
cout << endl;

结果:
这里写图片描述

优先输出小数据 即小顶堆

  • priority_queue<int, vector<int>, greater<int> > p;
  • 使用 greater<int> . 即改用 operator >

举例

priority_queue<int, vector<int>, greater<int>> pq2; // 最小堆

std::cout << "start..." << endl;
for (int i = 0; i < 10; i++) {
    int t = rand() % 100;
    std::cout << t << ends;
    pq2.push(t);
}
std::cout << endl;

while (!pq2.empty())
{
    cout << pq2.top() << ends;
    pq2.pop();
}
cout << endl;

结果:
这里写图片描述

自定义优先级 重载默认的 < 符号

1. 使用 funtion .

// 定义比较函数
// 后面一个表示栈顶元素? 所以这个是 "最小堆"
bool myCom(int a, int b) {
    return a % 10 > b % 10;
}

// 使用
priority_queue<int, vector<int>, function<bool(int,int)>> pq3(myCom); 

std::cout << "start..." << endl;
for (int i = 0; i < 10; i++) {
    int t = rand() % 100;
    std::cout << t << ends;
    pq3.push(t);
}

std::cout << endl;

while (!pq3.empty())
{
    cout << pq3.top() << ends;
    pq3.pop();
}
cout << endl;

输出结果:
这里写图片描述

2. 自定义数据类型

#include<iostream>
#include<queue>
#include<cstdlib>
using namespace std;
struct Node{
    int x,y;
    Node(int a=0, int b=0):
        x(a), y(b) {}
};

struct cmp{
    bool operator()(Node a, Node b){
        if(a.x == b.x)  return a.y>b.y;
        return a.x>b.x;
    }
};

int main(){
    priority_queue<Node, vector<Node>, cmp>p;

    for(int i=0; i<10; ++i)
        p.push(Node(rand(), rand()));

    while(!p.empty()){
        cout<<p.top().x<<' '<<p.top().y<<endl;
        p.pop();
    }//while
    //getchar();
    return 0;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值