自学内容网 自学内容网

C++ 自定义类型list的排序案例

一、问题描述

  •   编写一个Person类,其中包含三种属性:姓名,年龄,身高。
  •   编写一个函数,可以对诸多Person对象进行排序,排序规则:先按照年龄升序。

二、代码实现

#include<iostream>
#include<string>
#include<list>
#include <algorithm>

using namespace std;

class Person {
private :
string name;
int age;
int length;
public :
Person(string n, int a, int l) : name(n), age(a), length(l) {}

void setName(string n) {
this->name = n;
}
string getName() {
return name;
}
void setAge(int a) {
this->age = a;
}
int getAge() {
return age;
}
void setLength(int l) {
this->length = l;
}
int getLength() {
return length;
}
};

//自定义比较函数,用于排序规则
bool comparePerson(Person &p1, Person &p2) {
return (p1.getAge() < p2.getAge());
}

//遍历输出列表人员信息
void printPeople(list<Person> &people) {
if (people.empty()) {
cout << "There is no person in this list." << endl;
return;
}

for (list<Person>::iterator it = people.begin();
it != people.end(); it++) {
cout << it->getName() << "今年" << it->getAge() << "岁, "
<< "身高" << it->getLength() << "cm" << endl;
}
}

int main() {
list<Person> people;

//初始化测试数据
Person p0("刘备", 35, 175);
Person p1("曹操", 45, 180);
Person p2("孙权", 40, 170);
Person p3("赵云", 25, 190);
Person p4("张飞", 35, 160);
Person p5("关羽", 35, 200);

//将测试数据加入队列
people.push_back(p0);
people.push_back(p1);
people.push_back(p2);
people.push_back(p3);
people.push_back(p4);
people.push_back(p5);

cout << "Before sort : " << endl;
printPeople(people);

people.sort(comparePerson);

cout << "After sort : " << endl;
printPeople(people);

return 0;
}

三、程序执行结果


原文地址:https://blog.csdn.net/JackerCSDN/article/details/140112431

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!