描述:将Person自定义数据类型进行排序,Person中有姓名,年龄,身高
排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序
#include<iostream>
using namespace std;
#include<list>
#include<string>
//创建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 printPerson(list<Person>& L)
{
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age
<<" 身高:" << (*it).m_height << endl;
}
}
bool myCompare(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容器存放类
list<Person>L;
//准备数据
Person p1("张三", 20, 180);
Person p2("李四", 21, 182);
Person p3("王五", 21, 170);
Person p4("赵六", 30, 165);
Person p5("唐僧", 21, 160);
Person p6("孙户", 40, 150);
//将数据存放到容器内
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
L.push_back(p6);
printPerson(L);
cout << "----------------------" << endl;
cout << "排序后:" << endl;
L.sort(myCompare);//自定义排序规则
printPerson(L);
}
int main()
{
test01();
system("pause");
return 0;
}