#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Person
{
public:
Person(string name,int age,int height){
m_name = name;
m_age = age;
m_height = height;
}
string m_name;
int m_age;
int m_height;
};
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;//按年龄升序排列
}
}
void test()
{
Person p1("刘备",35,175);
Person p2("曹操",45,188);
Person p3("孙权",48,170);
Person p4("赵云",25,198);
Person p5("张飞",35,160);
Person p6("关羽",35,200);
list<Person> myL;
myL.push_back(p1);
myL.push_back(p2);
myL.push_back(p3);
myL.push_back(p4);
myL.push_back(p5);
myL.push_back(p6);
for(list<Person>::iterator it = myL.begin();it != myL.end();it++){
cout<<"姓名: "<<it->m_name<<" 年龄 :"<<it->m_age<<" 身高 :"<<it->m_height<<endl;
}
cout<<"-----------------"<<endl;
//按年纪大小排序
myL.sort(compare);//使用list里面的成员函数,使用仿函数指定排序方法
for(list<Person>::iterator it = myL.begin();it != myL.end();it++){
cout<<"姓名: "<<it->m_name<<" 年龄 :"<<it->m_age<<" 身高 :"<<it->m_height<<endl;
}
}
int main()
{
test();
return 0;
}
C++ List中的排序使用实例
于 2022-05-06 17:16:50 首次发布