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

在C++中,sort 函数默认对元素进行升序排序,但它也允许我们通过自定义比较规则来实现更灵活的排序方式。这个功能通过传入一个比较函数、函数对象或Lambda表达式来实现。
你可以定义一个返回 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;
}
Lambda 写法更简洁,适合简单逻辑,也支持捕获外部变量。
立即学习“C++免费学习笔记(深入)”;
示例:按字符串长度排序:
#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;
}
适用于复杂逻辑或需要保存状态的情况。
示例:按模某个数的余数排序:
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 → 排序后按余数升序
常用于根据结构体的某个字段排序。
示例:
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)。
注意事项:以上就是c++++中sort函数怎么自定义排序_sort自定义排序规则实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号