自定义结构或类的比较

存放在数组或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<>()。

如果是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>v2

 

如果是用在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;//使用
...

 

posted @ 2014-08-12 21:52  Fanny123  阅读(218)  评论(0编辑  收藏  举报