首页 > 其他 > 详细

自定义compare 函数

时间:2016-03-14 07:05:13      阅读:224      评论:0      收藏:0      [点我收藏+]
//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(); } }

 

在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);
    }
};

 

自定义compare 函数

原文:http://www.cnblogs.com/XingyingLiu/p/5274416.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!