排序一个自定义类型person
首先按年龄排序,年龄相同再按身高排序
效果:
代码:
#include<iostream>
using namespace std;
#include<list>
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;
};
//指定paixuguize
bool ComporePerson(person& p1, person& p2)
{
//按年龄升序
if (p1.m_age == p2.m_age)
{
return p1.m_height > p1.m_height;
}
return p1.m_age<p2.m_age;
}
void printlist(const list<person>& L)
{
for (list<person>::const_iterator it = L.begin(); it != L.end(); it++)
{
cout << "姓名: " << (*it).m_name << "\t年龄:" << it->m_age << "\t身高:" << it->m_height << endl;;
}
cout << endl;
}
void test01()
{
list<person> L;
person p1("刘备",58,162);
person p2("关羽", 53, 172);
person p3("奶爸", 32, 192);
person p4("老板", 58, 152);
person p5("柏拉图", 58, 172);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
printlist(L);
cout << "排序后" << endl;
cout << "_________________________" << endl;
L.sort(ComporePerson);
printlist(L);
}
int main()
{
test01();
system("pause");
return 0;
}