1 #include <iostream>
2 #include <string>
3 #include <vector>
4 #include <algorithm>
5
6 using namespace std;
7
8 class Cat{
9 public:
10 int id;
11 string name;
12 int age;
13 Cat(int i,string n,int a){
14 id = i;
15 name =n;
16 = Age A;
. 17
18 is }
. 19 };
20 is
21 is / *
22 is implemented its comparison function:
23 Format:
24 bool compName (Obj1, Obj2);
25 Note:
26 1 function must return a bool value
27 2. If the function returns true it means that the parameter or standard ordered in this order (i.e., no swap), i.e., will return false the swap
28 third parameter as a function 3. sort (beginIndex, endIndex, compName) a;
29
30 * /
31 is BOOL myCompare ( A * CAT, CAT * B) {
32 // press in ascending order id
33 is IF (A-> id <B-> id) return to true ;
34 is the else IF (A-> ID> B-> ID) return to false ;
35 the else {
36 // same ID
37 [ // by lexicographically ordering the name
38 is IF (A-> name.compare (B-> name) < 0 ) return to true ;
39 the else IF (A-> name.compare (B-> name)> 0 ) return to false ;
40 the else {
41 is // same name, from small to large by age
42 is IF (A-> age <B- > Age) return to true ;
43 is IF (A-> Age> B-> Age) return to false ;
44 is the else {
45 // Age same
46 // return to true
47 return to true ;
48 }
49 }
50
51 is }
52 is }
53 is
54 is
55 int main () {
56 is Vector <Cat *> V;
57 is v.push_back ( new new Cat ( . 1 , " Jim " , . 1 ));
58 v.push_back ( new new Cat ( . 1 ,"Jima",1));
59 v.push_back(new Cat(1,"Jimb",1));
60 v.push_back(new Cat(1,"Jimc",1));
61 v.push_back(new Cat(1,"J",1));
62 v.push_back(new Cat(2,"Jim",1));
63 v.push_back(new Cat(2,"Jizzz",1));
64 v.push_back(new Cat(2,"Jim",2));
65 v.push_back(new Cat(2,"Jim",3));
66 sort(begin(v),end(v),myCompare);
67 for(int i=0;i<v.size();i++){
68 Cat * c = v[i];
69 cout<<c->id<<" "<<c->name<<" "<<c->age<<endl;
70 }
71
72 }
73
74 /*
75 output:
76 1 J 1
77 1 Jim 1
78 1 Jima 1
79 1 Jimb 1
80 1 Jimc 1
81 2 Jim 1
82 2 Jim 2
83 2 Jim 3
84 2 Jizzz 1
85
86 */