案例描述:将person自定义数据类型进行排序,person中属性有姓名,年龄,身高
排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序
//案例描述:将person自定义数据类型进行排序,person中属性有姓名,年龄,身高
//排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序
#include<iostream>
using namespace std;
#include<string>
#include<list>
class person
{
public:
person(string name, int age, int height)
{
this->name = name;
this->age = age;
this->height = height;
}
string name;
int age;
int height;
};
bool compare(person &p1,person &p2)
{
if (p1.age == p2.age)
{
return p1.height > p2.height;
}
else
{
return p1.age < p2.age;
}
}
void test1()
{
list<person> l;
person p1("张三", 25, 165);
person p2("李四", 35, 210);
person p3("王五", 35, 186);
person p4("赵六", 35, 189);
person p5("何九", 46, 164);
person p6("贾八", 49, 175);
person p7("权十", 49, 198);
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
l.push_back(p5);
l.push_back(p6);
l.push_back(p7);
for (list<person>::iterator it = l.begin(); it != l.end(); it++)
{
cout << " 姓名为: " << (*it).name << " 年龄为: " << (*it).age << " 身高为: " << it->height << endl;
}
//排序
cout << "--------------------------------------" << endl;
l.sort(compare);
for (list<person>::iterator it = l.begin(); it != l.end(); it++)
{
cout << " 姓名为: " << (*it).name << " 年龄为: " << (*it).age << " 身高为: " << it->height << endl;
}
}
int main()
{
test1();
return 0;
}