list容器排序案例:
实现要求:
1.用list容器存放自定义数据类型
2.在键盘上输入姓名、年龄、身高
3.排序年龄从小到大,如果年龄相同再按照身高排序从高到矮
#include<iostream>
using namespace std;
#include<string>
#include<list>
#define I 10
class Person
{
public:
string Name;
int Age;
float Height;
};
void PrintList(const list<Person>& L)
{
for (list<Person>::const_iterator it = L.begin(); it != L.end(); it++)
{
cout << "姓名:" << (*it).Name << " 年龄:" << it->Age << " 身高:" << it->Height << endl;
}
cout << endl;
}
bool SortPerson(Person &p1,Person &p2)
{
if (p1.Age == p2.Age)
{
return p1.Height > p2.Height;
}
else
{
return p1.Age < p2.Age;
}
}
void StePerson()
{
Person p;
list<Person>L;
for (int i = 0; i < I; i++)
{
cout << "输入姓名:";
cin >> p.Name;
cout << "输入年龄:";
cin >> p.Age;
cout << "输入身高:";
cin >> p.Height;
L.push_back(p);
}
PrintList(L);
//排序
cout << "排序后:" << endl;
L.sort(SortPerson);
PrintList(L);
}
int main()
{
StePerson();
system("pause");
return 0;
}