STL的qsort使用

void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) ); 
Sort elements of array
Sorts the num elements of the array pointed by base, each element size bytes long, using the comparator function to determine the order.

The sorting algorithm used by this function compares pairs of values by calling the specified comparator function with two pointers to elements of the array.

The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order.

Parameters

  
  
  
  
base
Pointer to the first element of the array to be sorted.
num
Number of elements in the array pointed by base.
size
Size in bytes of each element in the array.
comparator
Function that compares two elements. The function shall follow this prototype:

int comparator ( const void * elem1, const void * elem2 );

The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.

The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.

Return Value

(none) 
具体应用
//都是升序的comparator,要降序只需要将*A和*B反过来即可 //1.comparator of int and its example int num[100]; int cmp_int(const void* a, const void* b) { int* A = (int*)a; int* B = (int*)b; return *A - *B; } qsort(num,100,sizeof(num[0]),cmp_int); //2.comparator of double and its example double num[100]; int cmp_double( const void* a , const void* b ) { double* A = (double*)a; double* B = (double*)b; return *A > *B ? 1 : -1; //a little different } qsort(num,100,sizeof(num[0]),cmp_double); //3.comparator of char and its example char ch[100]; int cmp_char(const void* a, const void* b) { char* A = (char*)a; char* B = (char*)b; return *A - *B; } qsort(ch,100,sizeof(ch[0]),cmp_char); //4.comparator of char string and its example char word[200][10]; int cmp_string(const void* a,const void* b) { char* A = (char*)a; char* B = (char*)b; return strcmp(A, B); }//是针对字符串数组按字典排序,非string类型 qsort(word,200,sizeof(word[0]),cmp_string);//将200个单词按字典序排序 //5.结构体一级排序 struct In { double data; int other; } In s[100]; //按照data的值从小到大将结构体排序,若为其他类型可以参照基本类型comparator照葫芦画瓢 int cmp( const void *a ,const void *b) { In* A = (In*)a; In* B = (In*)b; return (*A).data > (*B).data ? 1 : -1; } qsort(s,100,sizeof(s[0]),cmp); //6.结构体二级排序 struct In { int x; int y; } In s[100]; //按照x从小到大排序,当x相等时按照y从大到小排序 int cmp( const void *a , const void *b ) { struct In *c = (In *)a; struct In *d = (In *)b; if(c.x != d.x) return c.x - d.x; else return d.y - c.y; } qsort(s,100,sizeof(s[0]),cmp);

你可能感兴趣的:(function,struct,String,Parameters,returning,Pointers)