问题描述:使用list容器存储自定义数据类型Person,其中Person中包含姓名以及年龄,使用sort对数据按照年龄从大到小排序,并且使用remove删除其中P4数据。
注意:要重载==号,以及提供排序方法
代码如下:
#include<iostream>
#include<list>
#include<string>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
this->m_Age = age;
this->m_Name = name;
}
string m_Name;
int m_Age;
};
bool operator==(const Person& p1, const Person& p2)
{
if (p1.m_Age == p2.m_Age && p1.m_Name == p2.m_Name)
{
return true;
}
else
{
return false;
}
}
bool myComparePerson(Person& p1, Person& p2)
{
return p1.m_Age > p2.m_Age;
}
void test05()
{
list<Person> L;
Person P1("Jhon", 15);
Person P2("Tom", 20);
Person P3("Mary", 13);
Person P4("Wjy", 25);
Person P5("独裁者", 5);
L.push_back(P1);
L.push_back(P2);
L.push_back(P3);
L.push_back(P4);
L.push_back(P5);
L.sort(myComparePerson);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << "姓名:" << it->m_Name << " " << "年龄:" << it->m_Age << endl;
}
cout << "--------------------------------------" << endl;
L.remove(P4);
for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
{
cout << "姓名:" << it->m_Name << " " << "年龄:" << it->m_Age << endl;
}
}
int main(void)
{
test05();
system("pause");
return 0;
}