1. 理解struct的sort自定义排序
在编程开发中,我们经常需要对结构体(struct)数组进行排序操作。系统提供的sort函数虽然强大,但默认只能对基本数据类型进行排序。当我们需要根据结构体的特定字段或多个字段组合来排序时,就需要用到自定义排序功能。
以C++为例,标准库中的sort函数默认使用<运算符进行比较,这对于自定义结构体显然不够灵活。我们需要通过以下两种方式之一来实现自定义排序:
- 在结构体内重载<运算符
- 提供自定义的比较函数或函数对象
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 自定义排序的实现方法
2.1 重载结构体的比较运算符
这是最直接的方式,通过在结构体内部重载<运算符,我们可以定义结构体之间的比较规则:
cpp复制struct Person {
string name;
int age;
double height;
// 重载<运算符
bool operator<(const Person& other) const {
// 先按年龄升序,年龄相同按身高降序
if(age != other.age)
return age < other.age;
return height > other.height;
}
};
使用时直接调用sort即可:
cpp复制vector<Person> people = {...};
sort(people.begin(), people.end());
2.2 使用自定义比较函数
如果不想或不能修改结构体定义,可以单独定义一个比较函数:
cpp复制bool comparePerson(const Person& a, const Person& b) {
// 按姓名升序排列
return a.name < b.name;
}
// 使用方式
sort(people.begin(), people.end(), comparePerson);
2.3 使用lambda表达式(C++11及以上)
现代C++更推荐使用lambda表达式,代码更简洁:
cpp复制sort(peop
