c/c++重载优先队列/set

注意
return中的 “>” 和 “<” 符号
优先队列中的排序大小与结构体里重载的符号相反
sort()函数中的排序大小与结构体里重载的符号一致

假设node是一个class类以下方式可以实现重载

struct cmp
{
    bool operator()(const node &a, const node &b){
        return a.val > b.val; // 大于表示小的在前,小根堆
        						// 对于sort则相反,大于表示大的在前,降序
    }
};
 
priority_queue<node, vector<node>, cmp> pq;

对于set重载,这个const 是必不可少的,少了其中一个都会报错:

struct cmp {
//下面形参的const 和 形参之后的 const都不可缺少,不然不能使用set成员函数
    bool operator () (const int& a, const int& b) const {
        return a > b;
    }
    //以下写法均不可行
    //bool operator () (int& a, int& b) {}
    //bool operator () (int& a, int& b) const {}
    //bool operator () (const int& a, const int& b) {}
    
};
set<int, cmp> st;
// 上面的重载相当于 set<int,greater<int>> st;
class Solution {
public:   
    int thirdMax(vector<int>& nums) {
        for (auto s : nums) st.insert(s);
        int i = 0;
        int res = INT_MIN;
        for (auto s : st) {
            if (s >= res) res = s;
            i++;
            if (i == 3) {
                res = s;
                break;
            }
        }
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

临江浪怀柔ℳ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值