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
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;//使用 ...