自定义compare 函数

//priority queue 可以用自定义的compare类

struct compare { bool operator()(const int& l, const int& r) { return l > r; } };
int main(){    priority_queue<int,vector<int>, compare > pq; pq.push(2); pq.push(3); pq.push(3); pq.push(1); while(!pq.empty()){ cout<<pq.top()<<endl; pq.pop(); } }

 priority_queue 默认情况下最大值在最前!

 

在sort的时候,也可以自己定义比较函数,可以把比较的方法写成函数或者类:

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

然后就可以用自己写的方法去sort

int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

但是!

如果把比较函数写在类里,要把这个比较函数定义成static

http://stackoverflow.com/questions/29286863/invalid-use-of-non-static-member-function

 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };

class Solution {
    
public:
    static bool compare (const Interval &a, const Interval &b){
        return a.start<b.start;
    }

    void haha(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), compare);
    }
};

 

转载于:https://www.cnblogs.com/XingyingLiu/p/5274416.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值