自定義結構或類的比較

存放在數組或vector中的排序:

定義普通函數:

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 struct act{
 5     int num;
 6     int s;
 7     int e;
 8 };
 9 bool lessact(const act& a1,const act &a2){
10     return a1.e<a2.e;
11 }
12 int main() {
13 
14     act *all=new act[n];
15 
16     sort(all.begin(),all.end(),lessact);
17 
18 }

定義成員函數:

在函數內部定義<或者>,再在排序時候使用less<>(),或者greater<>()。ios

若是是greater,要注意頭文件:#include <functional>數組

 1 #include<iostream>
 2 #include<algorithm>
 3 #include <functional>
 4 using namespace std;
 5 
 6 struct Thing
 7 {
 8     int v;//單價
 9     int w;//重量
10     bool operator<(const Thing& other)const{
11         return v < other.v;
12     }
13     bool operator>(const Thing& other)const{
14         return v > other.v;
15     }
16 };
17 
18 ...
19     sort(t, t + n, greater<Thing>());
20 
21 ...

若是是存放在vector中,甚至能夠直接比較兩個vector:v1>v2less

 

若是是用在set或者map中,則能夠定義單獨的struct或類,也能夠是成員函數

class SymbolLess : public std::binary_function<Symbol, Symbol, bool>{
public:  
    bool operator () (Symbol* lhs, Symbol* rhs) const  
    {  
        return lhs->getContent()< rhs->getContent();  
    }  
};  

...
set<Symbol*, SymbolLess> Symbols;//使用
...
相關文章
相關標籤/搜索