在C++中自定义sort排序规则可通过函数指针、lambda表达式或重载operator()实现,需满足严格弱序要求。

在C++中使用sort函数自定义比较规则,可以让排序按照我们指定的逻辑进行。默认情况下,sort按升序排列元素,但通过传入自定义的比较函数或函数对象,可以灵活控制排序方式。
可以写一个返回bool类型的函数,接收两个参数,当第一个参数应排在第二个之前时返回true。
示例:按整数降序排列
#include <algorithm><br>#include <vector><br>#include <iostream><br><br>bool cmp(int a, int b) {<br> return a > b; // 降序<br>}<br><br>int main() {<br> std::vector<int> vec = {3, 1, 4, 1, 5};<br> std::sort(vec.begin(), vec.end(), cmp);<br> for (int x : vec) std::cout << x << " "; // 输出: 5 4 3 1 1<br> return 0;<br>}C++11起支持lambda,写法更简洁,适合简单逻辑。
立即学习“C++免费学习笔记(深入)”;
示例:按字符串长度排序
#include <algorithm><br>#include <vector><br>#include <string><br>#include <iostream><br><br>int main() {<br> std::vector<std::string> words = {"hi", "hello", "cpp", "sort"};<br> std::sort(words.begin(), words.end(),<br> [](const std::string& a, const std::string& b) {<br> return a.length() < b.length();<br> });<br> for (const auto& w : words)<br> std::cout << w << " "; // 输出: hi cpp sort hello<br> return 0;<br>}operator()
适用于复杂逻辑或多处复用的情况。
示例:按二维点到原点距离排序
#include <algorithm><br>#include <vector><br>#include <cmath><br><br>struct Point {<br> int x, y;<br>};<br><br>struct CmpByDistance {<br> bool operator()(const Point& a, const Point& b) {<br> return (a.x*a.x + a.y*a.y) < (b.x*b.x + b.y*b.y);<br> }<br>};<br><br>int main() {<br> std::vector<Point> points = {{3,4}, {1,1}, {0,2}};<br> std::sort(points.begin(), points.end(), CmpByDistance());<br> // 排序后顺序: (1,1), (0,2), (3,4)<br> return 0;<br>}自定义比较函数必须满足“严格弱序”关系:
true(即cmp(a,a)必须为false)cmp(a,b)为true,则cmp(b,a)应为false
<=或>=,只用<或>
基本上就这些。根据场景选择函数、lambda或仿函数,注意逻辑正确性即可。
以上就是C++怎么自定义sort函数的比较规则_C++ sort自定义比较函数写法示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号