C++中sort函数支持自定义排序规则,可通过函数指针、Lambda表达式或函数对象实现。1. 函数指针:定义bool cmp(T a, T b)函数,如降序排序返回a>b;2. Lambda表达式:语法简洁,适合简单逻辑,如按字符串长度升序排序;3. 函数对象:重载operator(),可保存状态,如按模数余数排序;4. 结构体排序:通过字段比较,如学生按分数降序排列。需满足严格弱序,避免修改外部变量。

在C++中,sort 函数默认对元素进行升序排序,但它也允许我们通过自定义比较规则来实现更灵活的排序方式。这个功能通过传入一个比较函数、函数对象或Lambda表达式来实现。
1. 使用函数指针自定义排序规则
你可以定义一个返回 bool 类型的函数,接收两个参数,用于判断第一个参数是否应该排在第二个参数之前。
示例:对整数数组进行降序排序:
#include <algorithm>
#include <vector>
#include <iostream>
bool cmp(int a, int b) {
return a > b; // 返回 true 表示 a 应该排在 b 前面
}
int main() {
std::vector<int> vec = {5, 2, 8, 1, 9};
std::sort(vec.begin(), vec.end(), cmp);
for (int x : vec) std::cout << x << " ";
// 输出:9 8 5 2 1
return 0;
}
2. 使用 Lambda 表达式(推荐)
Lambda 写法更简洁,适合简单逻辑,也支持捕获外部变量。
立即学习“C++免费学习笔记(深入)”;
需要创建、读取、编辑或处理 Word 文档(.docx / .dotx)时使用。触发词:'Word'、'word 文档'、'.docx'、'生成报告'、'制作合同/简历/方案/说明书'、'提取 word 内容'、'在文档里查找替换'、'给文档加页眉页脚/目录/表格'。也用于把任意内容排版成一份正式的 Word 文件。不要用它处理 PDF、Excel 或无关编程任务。中文创作场景尤其适合:小说大纲稿、投稿文档、合同、简历、工作总结。
按字符串长度排序:
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
int main() {
std::vector<std::string> words = {"apple", "hi", "banana", "go"};
std::sort(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
for (const auto& w : words)
std::cout << w << "(" << w.length() << ") ";
// 输出:hi(2) go(2) apple(5) banana(6)
return 0;
}
3. 使用函数对象(仿函数)
适用于复杂逻辑或需要保存状态的情况。
示例:按模某个数的余数排序:
struct ModCompare {
int mod;
ModCompare(int m) : mod(m) {}
bool operator()(int a, int b) const {
return (a % mod) < (b % mod);
}
};
// 使用:
std::vector<int> nums = {10, 3, 7, 14, 5};
std::sort(nums.begin(), nums.end(), ModCompare(5));
// 按 %5 的结果排序:10%5=0, 5%5=0, 14%5=4, 3%5=3, 7%5=2 → 排序后按余数升序
4. 对结构体或类自定义排序
常用于根据结构体的某个字段排序。
示例:
struct Student {
std::string name;
int score;
};
std::vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 70}};
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.score > b.score; // 按分数降序
});
也可以先按一个字段排序,再按另一个字段(稳定排序建议用 stable_sort)。
注意事项:- 比较函数必须满足“严格弱序”:即 cmp(a,a) 为 false;若 cmp(a,b) 为 true,则 cmp(b,a) 必须为 false。
- 不要在比较函数中修改外部数据,可能导致未定义行为。
- Lambda 若不捕获变量,可直接作为函数指针使用。


















