c++ sort函数怎么自定义比较函数_c++排序自定义规则实现

c++kquote>答案是使用比较函数、函数对象或Lambda表达式可实现std::sort自定义排序。1. 函数指针用于基本类型降序或自定义逻辑;2. 结构体排序需按字段写比较函数,如先按分数后按名字;3. Lambda表达式更简洁,推荐现代C++使用;4. 函数对象适合有状态或复用场景。

在C++中使用std::sort函数时,如果需要按照自定义规则排序,可以通过传入比较函数、函数对象(仿函数)或Lambda表达式来实现。默认情况下,sort按升序排列基本类型,但对复杂数据类型(如结构体、类对象)或特殊排序需求,必须自定义比较逻辑。

1. 使用函数指针作为比较函数

最常见的方式是定义一个返回bool类型的函数,接受两个参数,当第一个参数应排在第二个之前时返回true

// 按整数降序排列
```cpp bool cmp(int a, int b) { return a > b; // a 在 b 前面的条件 } std::vector nums = {3, 1, 4, 1, 5}; std::sort(nums.begin(), nums.end(), cmp); ```

2. 结构体或类对象排序

对自定义类型排序时,比较函数需根据具体字段判断顺序。

```cpp struct Student { std::string name; int score; };

// 按分数从高到低,分数相同时按名字字典序 bool cmpStudent(const Student& a, const Student& b) { if (a.score != b.score) { return a.score > b.score; } return a.name

std::vector students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 85}}; std::sort(students.begin(), students.end(), cmpStudent);

3. 使用Lambda表达式(推荐现代C++写法)

Lambda更简洁,适合简单逻辑,可直接在sort调用中定义。

```cpp std::vector nums = {3, 1, 4, 1, 5}; std::sort(nums.begin(), nums.end(), [](int a, int b) { return a < b; // 升序 });

对结构体:

```cpp std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.score == b.score) { return a.name b.score; }); ```

4. 使用函数对象(仿函数)

适用于需要状态或复用的场景。

```cpp struct CmpByLength { bool operator()(const std::string& a, const std::string& b) { return a.length() std::vector<:string>words = {"hi", "hello", "c++"}; std::sort(words.begin(), words.end(), CmpByLength());

注意事项:
  • 比较函数必须满足严格弱序:即cmp(a,a)必须为false,且若cmp(a,b)为true,则cmp(b,a)不能为true。
  • 传递给sort的比较逻辑应保证可预测、无副作用。
  • 使用引用传参(尤其是结构体)避免拷贝开销。
基本上就这些。根据实际需求选择合适方式,Lambda最常用也最直观。