sort函数时由低到高排序
struct { int a; int b; }s[100]; 对于这个结构体数组,我想用sort函数给其中的a排序,但由于a和b是成组的,怎么能让a排序的时候,b跟着a?用sort函数
比如 a 1 5 3 2 4 b 7 8 9 0 6 我希望是 a 1 2 3 4 5 b 7 0 9 6 8 而用sort函数排序a却是 a 1 2 3 4 5 b 7 8 9 0 6 #include<stdio.h> #include<algorithm> using namespace std; struct { int a; int b; }s[10]; int main() { int i; for(i=0;i<5;i++) scanf("%d%d",&s[i].a,&s[i].b); int *p1=&s[0].a; int *p2=&s[5].a; sort(p1,p2); for(i=0;i<5;i++) printf("%d %d\n",s[i].a,s[i].b); return 0; } 就比如这样,不行。
#include<stdio.h> #include<algorithm> using namespace std; struct STRUCT_NUM { int a; int b; } s[10]= { 1,7, 5,8, 3,9, 2,0, 4,6, 1,2 }; int cmp(const STRUCT_NUM& a,const STRUCT_NUM& b) { if(a.a==b.a) return a.b<b.b; else return a.a<b.a; } int main() { int i; sort(s,s+6,cmp); for(i=0; i<6; i++) printf("%d %d\n",s[i].a,s[i].b); return 0; }