使用cpp的优先队列

本文展示了如何利用C++中的`priority_queue`实现最大堆和最小堆。通过示例,创建了一个根据名字长度排序的山峰(最大堆),并分别创建了存储整数的最大堆和最小堆。程序输出了排序后的山峰名字和两个堆的元素。
摘要由CSDN通过智能技术生成
// implementing maxheap and min heap using priority queue

#include <iostream>
#include "queue"
#include "vector"
using namespace std;

class Mountain{
public:
    string name;
    int height;
public:
    Mountain(string arg_name, int arg_height):name(arg_name),height(arg_height){}

};

class CompareGreaterName{
public:
    bool operator()(const Mountain& a, const Mountain& b) const{
        // Mountain with smaller name goes below
        if (a.name.size()<b.name.size()) return true;
        return false;
    }
};


int main() {
    priority_queue<Mountain,vector<Mountain>,CompareGreaterName> pq_mountains;
    Mountain m1("K2",8611);
    Mountain m2("Kangchenjunga", 8586);
    Mountain m3("Everest", 8848);
    Mountain m4("Annapurna", 8091);

    pq_mountains.push(m1);
    pq_mountains.push(m2);
    pq_mountains.push(m3);
    pq_mountains.push(m4);

    cout<<"Arranging mountain name(s) based on the length (max_heap) of the names"<<endl;
    while(!pq_mountains.empty()){ // 按名字的长度排序
        Mountain mount = pq_mountains.top();
        pq_mountains.pop();
        cout<<mount.name<<" "<<mount.height<<endl;
    }

    priority_queue<int,vector<int>> pq_maxheap; // 最大堆
    pq_maxheap.push(5);
    pq_maxheap.push(2);
    pq_maxheap.push(7);
    pq_maxheap.push(13);
    pq_maxheap.push(11);
    cout<<"Elements in max heap:";
    while (!pq_maxheap.empty()){
        cout<<pq_maxheap.top()<<" ";
        pq_maxheap.pop();
    }

    priority_queue<int,vector<int>,greater<int>> pq_minheap; // 最小堆
    pq_minheap.push(5);
    pq_minheap.push(2);
    pq_minheap.push(7);
    pq_minheap.push(13);
    pq_minheap.push(11);
    cout<<"\nElements in min heap:";
    while (!pq_minheap.empty()){
        cout<<pq_minheap.top()<<" ";
        pq_minheap.pop();
    }

    return 0;
}

输出:

Kangchenjunga 8586
Annapurna 8091
Everest 8848
K2 8611
Elements in max heap:13 11 7 5 2
Elements in min heap:2 5 7 11 13

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值