priority_queue自定义struct的优先级设置写法

本文展示了一个使用C++实现的优先队列示例,包括如何定义自定义类型的优先级比较,以及如何使用预定义的比较函数来创建优先级高低不同的优先队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<queue>
using namespace std;
struct node{
    int x;
    int y;
    friend 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<int,vector<int>,greater<int> > que1;// 数字越小优先级越高
    priority_queue<int,vector<int>,less<int> > que2;// 数字越大优先级越高
    priority_queue<node> que;// 自定义结构体优先队列优先级
    node now1={2,3};
    node now2={1,4};
    node now3={5,11};
    node now4={2,4};
    node now5={2,5};
    que.push(now1);
    que.push(now2);
    que.push(now3);
    que.push(now4);
    que.push(now5);
    while(!que.empty())
    {
        node k=que.top();
        cout<<k.x<<" "<<k.y<<endl;
        que.pop();
    }
}

 

### C++ 中 `priority_queue` 和自定义比较器 在 C++ 的标准模板库(STL)中,`std::priority_queue` 是一种容器适配器,默认情况下它是一个最大堆。为了改变其行为并实现最小堆或其他排序逻辑,可以提供一个自定义的比较函数。 #### 自定义优先级队列 当创建 `std::priority_queue` 时,可以通过传递第三个参数来指定不同的比较方式: ```cpp #include <queue> #include <functional> struct Compare { bool operator()(const int& lhs, const int& rhs) const { return lhs > rhs; } }; std::priority_queue<int, std::vector<int>, Compare> minHeap; // 或者使用 lambda 表达式作为比较器 auto cmp = [](int a, int b){return a > b;}; std::priority_queue<int, std::vector<int>, decltype(cmp)> customPQ(cmp); ``` 上述代码展示了如何通过结构体或 Lambda 函数来自定义比较操作[^1]。 #### 排序算法中的重载函数 对于内置类型的数组或向量可以直接调用 `std::sort()` 进行升序排列;如果想要降序或者其他特定顺序,则需传入额外的谓词表达式给该函数: ```cpp #include<algorithm> #include<vector> bool compare(int a, int b){ return a>b; // 实现降序排序 } std::vector<int> vec={7,2,5,3}; std::sort(vec.begin(),vec.end(),compare); // 使用lambda简化写法 std::sort(vec.begin(), vec.end(), [](int a,int b)->bool{return a<b;} ); ``` 此部分说明了如何利用外部布尔返回值型的二元运算符来进行定制化排序[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值