C++:list容器自定义类型排序


#include <iostream>
#include <list>
#include <string>
using namespace std;

class Person
{
public:
	Person(string name, int age, int hight)
	{
		this->m_Name = name;
		this->m_Age = age;
		this->m_Hight = hight;
	}
	string m_Name;
	int m_Age;
	int m_Hight;
};

// 年龄降序  年龄相等时按身高升序
bool myCompare(Person &p1, Person &p2)
{
	if (p1.m_Age == p2.m_Age)
	{
		return p1.m_Hight < p2.m_Hight;		//按身高从小到大
	}
	else
		return p1.m_Age > p2.m_Age;		//按年龄从大到小
}
void test02()
{
	list<Person> L;
	Person p1("张三", 20, 170);
	Person p2("李四", 16, 177);
	Person p3("王五", 18, 156);
	Person p4("赵六", 18, 190);
	Person p5("陈七", 18, 178);

	L.push_back(p1);
	L.push_back(p2);
	L.push_back(p3);
	L.push_back(p4);
	L.push_back(p5);

	L.sort(myCompare);
	for (auto e : L)
	{
		cout << e.m_Name << " " << e.m_Age << " " << e.m_Hight << endl;
	}
}
int main()
{
	test02();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/feissss/article/details/88620689