c++sort函数自定义排序方式使用方法
时间: 2025-04-06 12:11:26 浏览: 29
### 自定义比较器的 C++ `std::sort` 使用方法
在 C++ 中,`std::sort` 是标准库中的一个高效排序算法,位于 `<algorithm>` 头文件中。它允许通过提供自定义比较器来实现特定的排序逻辑。
以下是使用自定义比较器的一个典型例子:
#### 定义结构体并重载运算符
可以通过重载小于 (`<`) 运算符来自定义排序规则。例如,假设有一个表示人的类 `Person`,我们希望按照年龄进行升序排序。
```cpp
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
struct Person {
std::string firstName;
std::string lastName;
int age;
// 构造函数
Person(std::string fn, std::string ln, int a) : firstName(fn), lastName(ln), age(a) {}
};
// 重载 '<' 运算符以便按年龄排序
bool operator<(const Person& lhs, const Person& rhs) {
return lhs.age < rhs.age; // 升序排列
}
void printPeople(const std::vector<Person>& people) {
for (const auto& person : people) {
std::cout << person.firstName << " " << person.lastName << ", Age: " << person.age << "\n";
}
}
```
调用 `std::sort` 对向量进行排序:
```cpp
int main() {
std::vector<Person> people = {
{"Alice", "Smith", 30},
{"Bob", "Johnson", 25},
{"Charlie", "Brown", 35}
};
std::sort(people.begin(), people.end()); // 默认使用 '<' 比较器
printPeople(people);
return 0;
}
```
#### 提供独立的比较函数
如果不想修改原始数据类型的接口,则可以传递一个单独的比较函数给 `std::sort`。下面是一个基于姓名首字母降序的例子:
```cpp
bool compareByLastNameDesc(const Person& lhs, const Person& rhs) {
return lhs.lastName > rhs.lastName; // 降序排列
}
int main() {
std::vector<Person> people = {
{"Alice", "Smith", 30},
{"Bob", "Johnson", 25},
{"Charlie", "Brown", 35}
};
std::sort(people.begin(), people.end(), compareByLastNameDesc);
printPeople(people);
return 0;
}
```
#### Lambda 表达式的应用
现代 C++ 支持 lambda 表达式作为更简洁的方式指定复杂条件下的排序行为。比如,先依据姓氏再依名字顺序排列:
```cpp
int main() {
std::vector<Person> people = {
{"Alice", "Smith", 30},
{"Bob", "Johnson", 25},
{"Charlie", "Brown", 35},
{"David", "Smith", 40} // 同一 last name 不同 first name
};
std::sort(people.begin(), people.end(),
[](const Person& lhs, const Person& rhs) -> bool {
if (lhs.lastName != rhs.lastName)
return lhs.lastName < rhs.lastName; // 姓氏优先级高
else
return lhs.firstName < rhs.firstName; // 名字次之
});
printPeople(people);
return 0;
}
```
上述代码展示了如何利用不同的方式定制化 `std::sort` 的功能[^1]。
阅读全文
相关推荐


















