#include <iostream>
#include <list>
#include <string>
#include <iomanip>
using namespace std;
class person
{
public:
person(string name, int age, float height)
{
this->m_name = name;
this->m_age = age;
this->m_height = height;
}
string m_name;
int m_age;
float m_height;
};
void printList(const list<person> &lst)
{
for (list<person>::const_iterator it = lst.begin(); it != lst.end(); it++)
{
cout << "Name: " << setiosflags(ios::left) << setw(10) << it->m_name
<< "Age: " << setiosflags(ios::left) << setw(5) << it->m_age
<< "\tHeight: " << fixed << setprecision(4) << it->m_height << endl;
}
}
bool compare(person& p1, person& p2)
{
if (p1.m_age == p2.m_age)
{
return p1.m_height < p2.m_height;
}
else return p1.m_age < p2.m_age;//scending order
}
void test1()
{
list<person> L;
person p1("Jerry", 16, 45.0);
person p2("Tom", 18, 75.0);
person p3("Yvie", 22, 160.0);
person p4("Mikael", 23, 165.0);
person p5("Zyaire", 10, 120.0);
person p6("Kim", 18, 156.0);
person p7("Bob", 18, 140.0);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
L.push_back(p6);
L.push_back(p7);
cout << "before sort: " << endl;
printList(L);
L.sort(compare);//仿函数
cout << endl << "after sort: " << endl;
printList(L);
}
int main()
{
test1();
system("pause");
return 0;
}
容器排序算法(自定义数据类型)
于 2022-03-29 23:46:37 首次发布