c++优先级队列自定义排序实现方式

1、使用常规方法实现

使用结构体实现自定义排序函数

2、使用lambda表达式实现

使用lambda表达式实现自定义排序函数

3、具体实现如下:

#include <iostream>
#include <queue>
#include <vector>

using namespace std;
using Pair = pair<int, int>;

class Test {
public:
    void FirstFun(const vector<Pair>& data) {
        priority_queue<Pair, vector<Pair>, Test::cmp> priorityQueue(data.begin(), data.end());
        cout << "First fun:" << endl;
        while (!priorityQueue.empty()) {
            const auto& topItem = priorityQueue.top(); // 使用常量引用
            cout << "(" << topItem.first << "," << topItem.second << ")" << endl;
            priorityQueue.pop();
        }
    }

    void SecondFun(const vector<Pair>& data) {
        auto cmp1 = [](const Pair& lhs, const Pair& rhs) {
            return lhs.second > rhs.second;
        };
        priority_queue<Pair, vector<Pair>, decltype(cmp1)> priorityQueue(data.begin(), data.end(), cmp1);
        cout << "Second fun:" << endl;
        while (!priorityQueue.empty()) {
            const auto& topItem = priorityQueue.top(); // 使用常量引用
            cout << "(" << topItem.first << "," << topItem.second << ")" << endl;
            priorityQueue.pop();
        }
    }

private:
    struct cmp {
        bool operator()(const Pair& litem, const Pair& ritem) {
            return litem.second > ritem.second;
        }
    };
};

int main() {
    Test test;
    vector<Pair> vec = {{6, 5}, {5, 2}, {3, 7}};
    test.FirstFun(vec);
    test.SecondFun(vec);
    return 0;
}

4、运行结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值