当前位置: 首页 > article >正文

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、运行结果:


http://www.kler.cn/news/319581.html

相关文章:

  • SDK3(note上)
  • NLP 文本分类任务核心梳理
  • Selenium点击元素的方法
  • 【深入学习Redis丨第六篇】Redis哨兵模式与操作详解
  • 电脑自带dll修复在哪里,dll丢失的6种解决方法总结
  • 免费与付费代理IP工具的优缺点分析
  • 遗忘的数学(拉格朗日乘子法、牛顿法)
  • (16)docker自动镜像打包脚本
  • 【Power Query】追加查询(动态列,动态路径)
  • 微软宣布弃用WSUS,企业用户尽早准备替换方案
  • [RabbitMQ] RabbitMQ介绍,安装与快速上手
  • 虚拟机开启网络代理设置,利用主机代理访问国外资源
  • Vue3:toRaw与markRaw
  • LeetCode 210. 课程表 II
  • yum 集中式安装 LNMP
  • 当电子设计竞赛照进生活!
  • 深入探秘 WorkManager:Android 异步任务管理的强大工具
  • 探索《藏汉翻译通》小程序:跨平台的藏文翻译利器
  • PostgreSQL - pgvector 插件构建向量数据库并进行相似度查询
  • django应用JWT(JSON Web Token)实战
  • C语言习题~day35
  • 产业报告 | 2024年中国机器人产业研究报告
  • 【裸机装机系列】15.kali(ubuntu)-重装linux步骤
  • android 14分屏实战之小米su7的3分屏实现方案讨论及线索征集
  • 智慧城市运营模式--政府和社会资本合作
  • 【Java数据结构】--- 优先级队列
  • fastjson的json字符串转List
  • 移动技术开发:ListView水果列表
  • C++ prime plus-7-編程練習
  • 2024年华为杯中国研究生数学建模竞赛E题(高速公路应急车道紧急启用模型)思路