C++中对vector自定义排序需提供比较函数,常用方法包括:1. 函数对象重载operator()实现升序比较;2. Lambda表达式简洁实现按成绩或名字长度排序;3. 普通函数传参方式;4. 调整比较条件实现降序。关键满足严格弱序要求。

在C++中对vector进行排序,通常使用std::sort函数。当vector中的元素是自定义类型(如结构体、类)或需要特殊排序规则时,就需要提供自定义的比较函数。以下是几种常见的实现方式。
定义一个函数对象,重载operator(),用于比较两个元素。
例如,对包含学生信息的vector按成绩升序排序:
#include <vector>
#include <algorithm>
#include <iostream>
struct Student {
std::string name;
int score;
};
struct CompareByScore {
bool operator()(const Student& a, const Student& b) const {
return a.score < b.score; // 升序
}
};
int main() {
std::vector<Student> students = {{"Alice", 85}, {"Bob", 72}, {"Charlie", 90}};
std::sort(students.begin(), students.end(), CompareByScore{});
for (const auto& s : students) {
std::cout << s.name << ": " << s.score << "\n";
}
return 0;
}
Lambda更简洁,适合简单的比较逻辑。
立即学习“C++免费学习笔记(深入)”;
继续上面的例子,用lambda实现相同功能:
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.score < b.score;
});
如果想按名字长度排序,可以写成:
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.name.size() < b.name.size();
});
也可以定义独立的比较函数,传给sort。
bool compareByName(const Student& a, const Student& b) {
return a.name < b.name;
}
// 调用
std::sort(students.begin(), students.end(), compareByName);
注意:函数必须接受两个const引用参数,返回bool值。
若要降序排列,只需调整比较条件。
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.score > b.score; // 降序
});
或者使用std::greater配合基础类型,但自定义类型仍需手动指定逻辑。
掌握这些方法后,就能灵活控制vector中任意类型的排序行为。关键是确保比较函数满足“严格弱序”:即对于任意a、b,不能同时满足comp(a,b)和comp(b,a),且具有可传递性。
基本上就这些,不复杂但容易忽略细节。
以上就是C++如何自定义vector的排序函数_C++容器排序与自定义比较方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号