#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<list>
#include<string>
using namespace std;
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;
};
bool mycomparePerson(Person& p1, Person& p2)
{
if (p1.m_Age == p2.m_Age)
{
return p1.m_Height > p2.m_Height;
}
else
{
return p1.m_Age< p2.m_Age;
}
}
void printListPerson(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;
}
}
void test()
{
list<Person>L;
Person p1("LiLy",10,110);
Person p2("Lisa", 20,120);
Person p3("Jennie",17,180);
Person p4("Rose", 19,180);
Person p5("Jisso", 28,175);
Person p6("Hong", 28,160);
Person p7("Wei", 28,196);
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);
L.sort(mycomparePerson);
printListPerson(L);
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}
利用C++中list.sort()对自定义Person()数据类型排序,年龄从小到大排序,如果年龄相同则按照身高从大到小排序,代码如上
输出如下:
所有的身高输出全是-842150451
求大佬帮助分析一下,这是什么原因,怎么修改?