c++ sort自定义排序
介绍
如何使用c++ STL中的sort函数去排序一些结构体类型的数据呢?
这里可以采用自定义比较函数的方法。
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef struct
{
int x;
int y;
} point;
//从小到大排序,以x为主序,y为次序
bool cmp1(point &a, point &b)
{
if (a.x == b.x)
{
return a.y < b.y;
}
return a.x < b.x;
}
//从大到小排序,以x为主序,y为次序
bool cmp2(point &a, point &b)
{
if (a.x == b.x)
return a.y > b.y;
return a.x > b.x;
}
int main()
{
int n = 10;
point p[10];
for (int i = 0; i < 10; i++)
{
p[i].x = rand() % 10 + 1;
p[i].y = rand() % 10 + 1;
cout << p[i].x << " " << p[i].y << endl;
}
cout << "the sort's result:............." << endl;
sort(p, p + 10, cmp2);
for (int i = 0; i < 10; i++)
cout << p[i].x << " " << p[i].y << endl;
return 0;
}
值得关注的地方就是两个
cmp1
和cmp2
函数,
-
cmp1
希望用来实现从小到大排序 -
cmp2
希望用来实现从大到小排序
补充:
突然想起个了注意事项,要记得把是否相等的判断写在大小判断的前面
顺序不可乱
本文作者:守护但米酒e
本文链接:https://www.cnblogs.com/xjy881/p/16366005.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步