声明:本机无C++环境,以下代码均没有编译测试,最近golang写的比较多,语法可能会有问题,请自行测试代码
sort排序函数简单使用
#include <bits/stdc++.h>
using namespace std;
int a[100];
bool cmp1(int x,int y) {
return x > y;
}
bool cmp2(int x,int y) {
return x < y;
}
int main()
{
//sort简单用法
int n;
scanf("%d",&n);
/*
1到n输入
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+1+n); //默认从小到大排序
*/
/*
0 到 n-1 输入
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
*/
//从大到小排序需要写自定义优先级函数
sort(a,a+n,cmp1); //采用cmp1函数排序 从大到小
sort(a,a+n,cmp2); //采用cmp2函数排序 从小到大
return 0;
}
结构体的自定义排序
例如 对于时间排序 年月日
#include <bits/stdc++.h>
using namespace std;
/*
//结构体排序两种写法 写法1 结构体内部 重载<运算符
struct node {
int year,month,day;
node() {year=0,month=0,day=0;}
node(int y,int m,int d) { year=y,month=m,day=d;}
bool operator< (const node &p) const { //重载<函数 内部写小于逻辑
if (year == p.year && month == p.month) {
return day < p.day;
}
if (year == p.year) {
return year < p.year;
}
return year < p.year;
}
};
//写法2 定义结构体后 写自定义排序函数
struct node {
int year,month,day;
node() {year=0,month=0,day=0;}
node(int y,int m,int d) { year=y,month=m,day=d;}
};
bool cmp(const node &p,const node &q) { //语句不同 实现排序效果同方法1 const不可省略
if (p.year != q.year) return p.year < q.year;
if (p.month != q.month) return p.month < q.month;
return p.day < q.day;
}
*/
node t[100];
int main()
{
t[0] = node{2019,1,20};
t[1] = node{2019,1,22};
t[2] = node{2018,2,1};
t[3] = node{2020,1,1};
/* 方法1
sort(t,t+4);
方法2
sort(t,t+4,cmp);
*/
for (int i=0;i<4;i++) {
printf("%d %d %d\n",t[i].year,t[i].month,t[i].day);
}
return 0;
}