案例描述:将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高

排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序

注意事项:因为list的迭代器不支持随机访问,所以不能使用标准算法,只能使用list自带的成员函数sort

所有不支持随机访问迭代器的容器,都不可以使用标准算法

代码如下:

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

class Person
{
public:
	Person(int age,string name,int hight)
	{
		this->m_age = age;
		this->m_name = name;
		this->m_hight = hight;
	}

	int m_age;
	string m_name;
	int m_hight;
};


void print(list<Person> &p)
{
	for (list<Person>::iterator it = p.begin(); it != p.end(); it++)
	{
		cout << "姓名:" << it->m_name << " 年龄:" << it->m_age << " 身高:" << it->m_hight << endl;
	}

}


bool compare(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 test01()
{
	list<Person> p;

	Person p1(35, "张飞", 165);
	Person p2(35, "关羽", 200);
	Person p3(35, "刘备", 175);
	Person p4(25, "赵云", 190);
	Person p5(45, "曹操", 170);

	p.push_back(p1);
	p.push_back(p2);
	p.push_back(p3);
	p.push_back(p4);
	p.push_back(p5);
	print(p);

	cout << "---------------" << endl;
	cout << "排序后:" << endl;
	p.sort(compare);
	print(p);
}



int main()
{
	test01();
	system("pause");
	return 0;
}

测试结果:

总结:

1.对于自定义数据类型,必须要指定排序规则,否则编译器不知道如何进行排序。

2.高级排序只是在排序规则上再进行一次逻辑规则制定。

更多推荐