#define NELEMS(array) (sizeof(array)/sizeof(array[0]))
//scmp: string compare of *p1 and *p2
//p1 p2是是字符串数组的一个元素的指针。字符串数组char* str[](等价于char** str)
int scmp(const void *p1, const void *p2){
char *v1;//字符串
char *v2;
v1 = *(char **)p1;//为什么是char**---因为-q s o r t传递的是数组里元素的地址,
//也就是说,是&str[i](类型为char**)而不是str[i](类型为char*)
//而str[i]是char*
v2 = *(char **)p2;
return strcmp(v1,v2);
}
//mian
//char* str[] = {{"asd"},{"adf"},{"key"},{"yue"},{"ber"},{"mew"}};
char *str[]={"red","yellow","blue","white","black"};
int N = NELEMS(str);
cout<<"字符串数组的元素个数 = "<<N<<endl;
qsort(str,N,sizeof(str[0]),scmp);
//C++中是sort()
cout<<"字符串 : "<<endl;
for(int i=0; i<N; i++){
cout<<str[i]<<" ";
}
cout<<endl;
C中自带的排序函数qsort
最新推荐文章于 2024-03-11 13:35:27 发布