-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path35_list_排序案例.cpp
77 lines (65 loc) · 1.52 KB
/
35_list_排序案例.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <list>
using namespace std;
// list 排序案例
// 案例描述:将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高
// 排序规则:按照年龄进行升序,如果年龄相同则按身高进行降序
class Person
{
public:
Person(string name, int age, int height)
{
this->m_Name = name;
this->m_Age = age;
this->m_Height = height;
}
string m_Name;
int m_Age;
int m_Height;
};
void printPersonList(const list<Person> &lst)
{
for (list<Person>::const_iterator it = lst.begin(); it != lst.end(); it++)
{
cout << "姓名:" << (*it).m_Name
<< " 年龄:" << it->m_Age
<< " 身高:" << it->m_Height
<< endl;
}
}
// 指定排序顺序
bool comparePerson(Person &p1, Person &p2)
{
// 按年龄升序
if (p1.m_Age == p2.m_Age)
{
// 年龄相同,按身高降序
return p1.m_Height > p2.m_Height;
}
return p1.m_Age < p2.m_Age;
}
void test01()
{
list<Person> L;
Person p1("A", 35, 175);
Person p2("B", 25, 178);
Person p3("C", 40, 170);
Person p4("D", 38, 180);
Person p5("E", 35, 165);
Person p6("F", 35, 170);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
L.push_back(p6);
printPersonList(L);
cout << "------排序后------" << endl;
L.sort(comparePerson);
printPersonList(L);
}
int main()
{
test01();
return 0;
}