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
希望用来实现从大到小排序
补充:
突然想起个了注意事项,要记得把是否相等的判断写在大小判断的前面
顺序不可乱