C++ //排序案列 //描述:将person自定义数据类型进行排序,Person中有属性 姓名,年龄,身高 //排序规则: 按照年龄进行的升序,如果年龄相同按照身高进行降序

 1 //排序案列 
 2 //描述:将person自定义数据类型进行排序,Person中有属性 姓名,年龄,身高
 3 //排序规则: 按照年龄进行的升序,如果年龄相同按照身高进行降序
 4 
 5 #include<iostream>
 6 #include<string>
 7 #include<algorithm>
 8 #include<list>
 9 
10 using namespace std;
11 
12 
13 //person类
14 class Person
15 {
16 public:
17     Person(string name, int age,int height)
18     {
19         this->m_Name = name;
20         this->m_Age = age;
21         this->m_Height = height;
22     }
23 
24 
25     string m_Name;   //姓名
26     int m_Age;      //年龄
27     int m_Height;   // 身高
28 };
29 
30 //指定排序规则
31 
32 bool comparePerson(Person & p1, Person& p2)
33 {
34     //按照年龄作为升序
35     if (p1.m_Age == p2.m_Age)
36     {
37         //年龄相同
38         return p1.m_Height > p2.m_Height;
39     }
40     else
41     {
42         return  p1.m_Age < p2.m_Age;
43     }
44     
45 }
46 void test01()
47 {
48     list<Person>L1;
49 
50     //准备数据
51     Person p1("刘备", 35, 175);
52     Person p2("曹操", 45, 180);
53     Person p3("孙权", 40, 170);
54     Person p4("赵云", 35, 190);
55     Person p5("张飞", 25, 160);
56     Person p6("关羽", 35, 200);
57 
58 
59     //插入数据
60     L1.push_back(p1);
61     L1.push_back(p2);
62     L1.push_back(p3);
63     L1.push_back(p4);
64     L1.push_back(p5);
65     L1.push_back(p6);
66 
67     for (list<Person>::iterator it = L1.begin(); it != L1.end(); it++)
68     {
69         cout << "姓名:" << (*it).m_Name << "  年龄:" << it->m_Age << "  身高:" << it->m_Height << endl;
70 
71     }
72 
73     //排序
74     cout << "-------------------------------------" << endl;
75     cout << "排序后:" << endl;
76 
77     L1.sort(comparePerson);
78     for (list<Person>::iterator it = L1.begin(); it != L1.end(); it++)
79     {
80         cout << "姓名:" << (*it).m_Name << "  年龄:" << it->m_Age << "  身高:" << it->m_Height << endl;
81 
82     }
83 }
84 int main()
85 {
86 
87     test01();
88 }

 

posted on 2021-08-15 15:46  Bytezero!  阅读(205)  评论(0编辑  收藏  举报