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

在C++中对vector进行排序,通常使用std::sort函数。当vector中的元素是自定义类型(如结构体、类)或需要特殊排序规则时,就需要提供自定义的比较函数。以下是几种常见的实现方式。
1. 使用函数对象(仿函数)
定义一个函数对象,重载operator(),用于比较两个元素。
例如,对包含学生信息的vector按成绩升序排序:
#include #include #include 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 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;}
2. 使用Lambda表达式
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(); });
3. 使用普通函数
也可以定义独立的比较函数,传给sort。
bool compareByName(const Student& a, const Student& b) { return a.name < b.name;}// 调用std::sort(students.begin(), students.end(), compareByName);
注意:函数必须接受两个const引用参数,返回bool值。
4. 逆序排序
若要降序排列,只需调整比较条件。
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++容器排序与自定义比较方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1483702.html
微信扫一扫
支付宝扫一扫