list容器对自定义数据类型排序,删除

问题描述:使用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;
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值