C++ sort函数怎么用_C++ STL排序算法自定义比较函数教程

std::sort是C++ STL中用于高效排序的函数,定义在头文件中,支持基本类型和自定义类型的排序。1. 对基本类型如int、double,默认使用升序排列,可通过std::greater实现降序。2. 对结构体或复杂对象,需提供自定义比较函数,该函数返回bool值表示第一个参数是否应排在第二个之前,例如按学生成绩从高到低排序。3. C++11起推荐使用Lambda表达式实现灵活排序逻辑,如先按分数降序再按名字升序。4. 注意事项包括:比较函数必须满足严格弱序;建议使用const引用避免拷贝;std::sort不保证稳定性,需稳定时用std::stable_sort;仅适用于支持随机访问迭代器的容器如vector,list应使用其成员函数sort。掌握这些用法可应对各类排序需求。

在C++中,std::sort 是 STL 算法库中最常用的排序函数之一。它定义在 gorithm> 头文件中,可以对数组、vector 等容器中的元素进行高效排序。默认情况下,它按升序排列,但你也可以通过自定义比较函数来控制排序规则。

基本用法:对基本类型排序

对 int、double 等基本数据类型排序时,直接使用 std::sort 即可:

#include 
#include 
#include 

int main() { std::vector nums = {5, 2, 8, 1, 9}; std::sort(nums.begin(), nums.end()); // 升序 // 输出: 1 2 5 8 9

std::sort(nums.begin(), nums.end(), std::greaterzuojiankuohaophpcnintyoujiankuohaophpcn()); // 降序
// 输出: 9 8 5 2 1

}

自定义比较函数:对结构体或复杂对象排序

当你需要对结构体、类对象或有特定排序逻辑的数据进行排序时,就需要传入自定义的比较函数。这个函数要返回布尔值,表示第一个参数是否“应该排在”第二个参数之前。

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

// 自定义比较函数:按分数从高到低排序 bool cmp(const Student& a, const Student& b) { return a.score > b.score; // 分数高的在前 }

int main() { std::vector students = { {"Alice", 85}, {"Bob", 92}, {"Charlie", 78} };

std::sort(students.begin(), students.end(), cmp);

// 结果: Bob(92), Alice(85), Charlie(78)

}

使用 Lambda 表达式(推荐)

C++11 起支持 Lambda,写起来更简洁,尤其适合简单排序逻辑:

std::vector students = {/* ... */};

// 按名字字母顺序排序 std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { return a.name < b.name; });

// 先按分数降序,分数相同时按名字升序 std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.score != b.score) return a.score > b.score; return a.name < b.name; });

注意事项

  • 比较函数必须严格弱排序(strict weak ordering),不能写错逻辑导致死循环或崩溃。
  • 若使用自定义函数或 lambda,参数建议用 const 引用,避免拷贝开销。
  • std::sort 不保证稳定排序;如需稳定排序,使用 std::stable_sort。
  • 只能用于支持随机访问迭代器的容器(如 vector、array),不适用于 list(list 有自己的 sort 成员函数)。

基本上就这些。掌握好自定义比较方式,就能灵活应对各种排序需求了。