c++学习之list容器排序

it2025-07-20  6

一、排序案例

案例描述 将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高。 排序规则 按照年龄进行排序,如果年龄相同按照身高及进行降序。

二、代码示例

#include <iostream> #include <queue> #include <algorithm> #include <string> #include <list> 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; }; void print(const list<Person>& l) { for(list<Person>::const_iterator it = l.begin(); it != l.end(); it++) { cout<< it->m_name <<" "<<it->m_age<<" "<<it->m_height<< endl; } cout << endl; } bool myCompare(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 test2() { //默认构造 list<Person>l; Person p1("lcl",23,169); Person p2("xqq",20,164); Person p3("hqq",22,170); Person p4("wxr",22,165); Person p5("lxw",23,169); l.push_back(p1); l.push_back(p2); l.push_back(p3); l.push_back(p4); l.push_back(p5); print(l); l.sort(myCompare); print(l); } int main() { test2(); return 0; }

三、结果输出

最新回复(0)