#include<iostream> #include<algorithm> #include<cstdio> using namespace std; int a[10]= {5435,-532,9,4,-94,9435,0,-43,-47,43}; bool cmp1(int x,int y) { return x>y; } bool cmp2(int x,int y) { if(x<0 && y<0) return x<y; if(x>=0 && y>=0) return x>y; return x<y; } int main() { int i,n; n=10; sort(a,a+n); //默认从小到大 for(i=0; i<n; i++) printf("%d ",a[i]); printf("\n"); sort(a,a+n,cmp1); //重载 for(i=0; i<n; i++) printf("%d ",a[i]); printf("\n"); sort(a,a+n,cmp2); for(i=0; i<n; i++) printf("%d ",a[i]); printf("\n"); return 0; }
#include<stdio.h> #include<algorithm> #include<cstring> using namespace std; typedef struct Data { int sorce; char name[20]; } DATA; bool cmp1(DATA a, DATA b) { return a.sorce < b.sorce; } //多个要求的sort排序 bool cmp2(DATA a, DATA b) { if(a.sorce==b.sorce) return strcmp(a.name,b.name)>0?0:1; return a.sorce<b.sorce; } int main(int argc, char *argv[]) { DATA data[5]; int i; for(i = 0; i < 5; i++) { scanf("%s %d", data[i].name, &data[i].sorce); } puts("输出结果:"); //sort(data, data + 5, cmp1); sort(data, data + 5, cmp2); for(i = 0; i < 5; i++) { printf("%s %13d\n", data[i].name, data[i].sorce); } return 0; } /********************* xiaoming 85 yangyang 86 honghong 96 xiaonang 96 aingming 86 ********************/