c++ stl sort example

c++ stl sort函数使用举例:

 1 #include <iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 #include<functional>
 5 
 6 using namespace std;
 7 
 8 class MyClass
 9 {
10     public:
11     MyClass(int a,int b):first(a),second(b){}
12     int first;
13     int second;
14     bool operator <(const MyClass &m)const
15     {
16         return first<m.first;//重写“<”
17     }
18 };
19 
20     bool LessSecond(const MyClass &m1,const MyClass &m2)
21     {
22         return m1.second<m2.second;
23     }
24 
25 int main()
26 {
27     vector<MyClass> vecMyclass;
28     int i=0;
29     for(i=0;i<=10;i++)
30     {
31         MyClass m(20-i,i*6);
32         vecMyclass.push_back(m);
33     }
34     cout<<"before sort is:"<<endl;
35     for(i=0;i<vecMyclass.size();i++)
36     cout<<vecMyclass[i].first<<","<<vecMyclass[i].second<<endl;
37     cout<<"after sort by first is:"<<endl;
38     sort(vecMyclass.begin(),vecMyclass.end());
39     for(i=0;i<vecMyclass.size();i++)
40     cout<<vecMyclass[i].first<<","<<vecMyclass[i].second<<endl;
41     sort(vecMyclass.begin(),vecMyclass.end(),LessSecond);
42     cout<<"after sort by second is:"<<endl;
43     for(i=0;i<vecMyclass.size();i++)
44     cout<<vecMyclass[i].first<<","<<vecMyclass[i].second<<endl;
45     return 0;
46 }

共勉。

原文地址:https://www.cnblogs.com/nannanITeye/p/3149089.html