C++ STL list自定义数据排序
#include <iostream>
using namespace std;
#include <list>
#include <string>
class PersonT
{
public:
PersonT(string strName, int iAge, int iHeight)
{
this->m_strName = strName;
this->m_iAge = iAge;
this->m_iHeight = iHeight;
}
string m_strName;
int m_iAge;
int m_iHeight;
};
void PrintList(list<PersonT>& pList)
{
for (list<PersonT>::iterator it=pList.begin(); it!=pList.end(); it++)
{
PersonT pIt = *it;
cout << "姓名:" << pIt.m_strName <<" 年龄:"<< pIt.m_iAge << " 身高:" << pIt.m_iHeight<< endl;
}
}
bool comparePerson(PersonT &p1, PersonT &p2)
{
if (p1.m_iAge == p2.m_iAge)
{
return p1.m_iHeight > p2.m_iHeight;
}
return p1.m_iAge < p2.m_iAge;
}
void test01()
{
list<PersonT> personList;
PersonT p1("刘备", 35, 175);
PersonT p2("曹操", 45, 160);
PersonT p3("孙权", 40, 170);
PersonT p4("赵云", 25, 190);
PersonT p5("张飞", 35, 170);
PersonT p6("关羽", 35, 200);
personList.push_back(p1);
personList.push_back(p2);
personList.push_back(p3);
personList.push_back(p4);
personList.push_back(p5);
personList.push_back(p6);
PrintList(personList);
personList.sort(comparePerson);
cout << "------------------------" << endl;
cout << "排序后" << endl;
PrintList(personList);
}
int main()
{
test01();
system("pause");
return 0;
}