1. 深入理解struct的sort自定义排序
在编程实践中,我们经常需要对结构体数组进行排序。系统提供的sort函数虽然强大,但默认只能对基本数据类型进行排序。当我们需要根据结构体的特定字段或多个字段组合排序时,就需要用到自定义排序功能。
以C++为例,标准库中的sort函数位于
提示:自定义排序的核心在于定义明确的比较规则,这个规则需要满足严格弱序(strict weak ordering)的要求,即对于任意两个元素a和b,比较函数必须能够明确判断a是否应该排在b前面。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 自定义排序的三种实现方式
2.1 重载小于运算符
最直接的方式是在结构体内部重载小于运算符。这种方法简洁明了,适用于结构体只有一种主要排序方式的场景。
cpp复制struct Student {
string name;
int score;
// 重载小于运算符,按分数从高到低排序
bool operator<(const Student& other) const {
return score > other.score; // 注意这里是>,实现降序排列
}
};
vector<Student> students;
sort(students.begin(), students.end());
注意:重载运算符时务必加上const修饰符,否则可能在编译时报错。这是许多初学者容易忽略的细节。
2.2 使用独立的比较函数
当需要多种排序方式,或者不想修改结构体定义时,可以使用独立的比较函数。这种方式更加灵活,可以根据不同场景使用不同的排序规则。
cpp复制struct Product {
string name;
double price;
int sales;
};
// 按价格升序排序
bool compareByPrice(const Product& a, const Product& b) {
return a.price < b.price;
}
// 按销量降序排序
bool compareBySales(const Product& a, const Product& b) {
return a.sales > b.sales;
}
vector<Product> products;
sort(products.begin(), products.end(), compareByPrice); // 按价格排序
sort(products.begin(), products.end(), compareBySales); // 按销量排序
2.3 使用Lambda表达式(C++11及以上)
现代C++推荐使用Lambda表达式实现自定义排序,这种方式代码更加紧凑,特别适合只需要使用一次的简单比较逻辑。
cpp复制struct Employee {
string name;
int age;
double salary;
};
vector<Employee> employees;
// 按年龄升序排序
sort(employees.begin(), employees.end(),
[](const Employee& a, const Employee& b) {
return a.age < b.age;
});
// 按薪资降序排序,如果薪资相同则按年龄升序排序
sort(employees.begin(), employees.end(),
[](const Employee& a, const Employee& b) {
if (a.salary != b.salary)
return a.salary > b.salary;
return a.age < b.age;
});
提示:Lambda表达式中的捕获列表可以为空([]),因为我们只需要比较两个参数,不需要访问外部变量。如果需要访问外部变量,可以在[]中指定。
