案例来自于黑马程序员的课件,因为找不到转载的网址,没办法只能标成原创。
这部分包括两个知识点:
1.自定义排序规则的编写
2. 自定义排序规则怎么嵌入到sort排序函数中
知识点1:
1.自定义排序规则的编写
类似于这样:person是自定义结构体
bool sort_list(person& p1, person& p2) {
if (p1.age == p2.age)
return p1.height < p1.height;
else
return p1.age < p2.age;
}
知识点2:
2. 自定义排序规则怎么嵌入到sort排序函数中
l.sort(sort_list); //直接把自定义排序规则写到sort函数的小括号里面即可,排序规则相当于是个伪函数,所以不用再加小括号了
#include<iostream>
#include<list>
#include<string>
using namespace std;
//自定义一个人类
struct person {
string name;
long age;
int height;
person(string name, long age, int height) {
this->name = name;
this->age = age;
this->height = height;
}
};
//自定义的排序规则,先按年龄排序,年龄相同时按照身高排序
//这个没办法使用模板,因为自定义类型的数据变量无法指定
bool sort_list(person& p1, person& p2) {
if (p1.age == p2.age)
return p1.height < p1.height;
else
return p1.age < p2.age;
}
void print_list(const list<person>l) {
for (list<person>::const_iterator it = l.begin(); it != l.end(); it++) {
cout << it->name << " " << it->age << " " << it->height << " " << endl;
}
cout << endl;
}
void test01() {
list<person>l;
//先定义N个实例化的人类
person p1("刘备", 35, 175);
person p2("曹操", 45, 180);
person p3("孙权", 40, 170);
person p4("赵云", 25, 190);
person p5("张飞", 35, 160);
person p6("关羽", 35, 200);
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
l.push_back(p5);
l.push_back(p6);
cout << "排序之前" << endl;
print_list(l);
l.sort(sort_list);
cout << "排序之后" << endl;
print_list(l);
}
int main() {
test01();
}