C++,STL 042(24.10.21)
内容
一道练习题。
(涉及list,sort)
题目(大致)
将Person自定义类型进行排序(Person中属性有姓名、年龄、身高),按照年龄进行升序,如果年龄相同则按照身高进行降序。
运行代码
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Person
{
public:
string m_Name;
int m_Age;
int m_Height;
public:
Person(string name, int age, int height)
{
this->m_Name = name;
this->m_Age = age;
this->m_Height = height;
}
};
bool comparePerson(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 test01()
{
list<Person> l;
Person p1("p1", 23, 166);
Person p2("p2", 23, 156);
Person p3("p3", 23, 178);
Person p4("p4", 33, 172);
Person p5("p5", 43, 190);
Person p6("p6", 45, 175);
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
l.push_back(p5);
l.push_back(p6);
cout << "排序前:" << endl;
for (list<Person>::iterator it = l.begin(); it != l.end(); it++)
{
cout << it->m_Name << " " << it->m_Age << " " << it->m_Height << endl;
}
l.sort(comparePerson);
cout << "排序后:" << endl;
for (list<Person>::iterator it = l.begin(); it != l.end(); it++)
{
cout << it->m_Name << " " << it->m_Age << " " << it->m_Height << endl;
}
}
int main()
{
test01();
return 0;
}