//注意:本题要求排序时,年龄相同按身高降序
//这时一个以上条件排序为高级排序
//高级排序即:在排序规则上再进行一次逻辑规则制定
#include<iostream>
using namespace std;
#include<list>
class person {
public:
person(string name, int age, int height) {
m_name = name;
m_height = height;
m_age = age;
}
string m_name;
int m_age;
int m_height;
};
//数据类型自定义时,此步骤必需
//指定排序规则
bool compareperson(person& p1, person& p2) {
//按照年龄 升序
//注意: 年龄相同时,按身高进行降序
if(p1.m_age!=p2.m_age)
return p1.m_age < p2.m_age;
else {
return p1.m_height > p2.m_height;
}
老师的写法,相等提前return结束
//if (p1.m_age == p2.m_age) {
// //年龄相同 身高降序
// return p1.m_height < p2.m_height;
//}
//return p1.m_age < p2.m_age;
}
void test01() {
list<person>L;
person p1("将军", 30, 189);
person p2("统领", 27, 185);
person p3("伍长", 34, 177);
person p4("亲卫", 18, 179);
person p5("校尉", 27, 182);
L.push_back(p1);
L.push_back(p2);
L.push_back(p3);
L.push_back(p4);
L.push_back(p5);
for (list<person>::iterator it = L.begin(); it != L.end(); it++) {
cout << "职位: " << (*it).m_name << " 年龄: " << (*it).m_age << " 身高: " << (*it).m_height << endl;
}
//排序
cout << "-----------------------------" << endl;
cout << "排序后: " << endl;
//排序对象为person自定义类,故排序时需要指定排序规则
L.sort(compareperson);
for (list<person>::iterator it = L.begin(); it != L.end(); it++) {
cout << "职位: " << (*it).m_name << " 年龄: " << (*it).m_age << " 身高: " << (*it).m_height << endl;
}
}
int main() {
test01();
}
c++笔记 STL list容器_排序案例
最新推荐文章于 2024-11-12 15:18:48 发布