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