qsort对结构体二级排序怎么实现
先对字符串排序,字符串相同然后对data排序struct In
{
int data;
char str[100];
}s[100];
#include <stdio.h> #include <stdlib.h> #include <string.h> struct In { int data; char str[100]; }; int In_Compare( const void* a, const void* b ) { struct In* pa = (struct In*)a; struct In* pb = (struct In*)b; int v = strcmp(pa->str,pb->str); if( v != 0 ) return v; if( pa->data < pb->data ) return -1; if( pa->data > pb->data ) return +1; return 0; } int main( void ) { struct In s[] = { {2,"b"}, {1,"b"}, {3,"a"} }; qsort( s, sizeof(s)/sizeof(*s), sizeof(*s), &In_Compare ); for( size_t i=0; i!=sizeof(s)/sizeof(*s); ++i ) printf( "%s --- %d\n", s[i].str, s[i].data ); return 0; }