zoukankan      html  css  js  c++  java
  • c++ qsort函数应用

    C++ qsort在"iostream" c在头文件stdlib.h中,strcmp在string.h中。下列例子默认从小到大排序即(a>b返回>0),反之从小到大排序

    1、对int类型数组排序

    int num[100]; 
    int cmp ( const void *a , const void *b ) 
    { 
        return *(int *)a - *(int *)b; 
    } 
    qsort(num,100,sizeof(num[0]),cmp); 

    2、对char类型数组排序(同int类型)

    char strs[100]; 
    int cmp( const void *a , const void *b ) 
    { 
        return *(char *)a - *(int *)b; 
    } 
    qsort(strs,100,sizeof(strs[0]),cmp); 

    3、对double类型数组排序(特别要注意)

    double dbs[100]; 
    int cmp( const void *a , const void *b ) 
    { 
        return *(double *)a > *(double *)b ? 1 : -1; 
    } 
    qsort(dbs,100,sizeof(dbs[0]),cmp); 

    4、对结构体一级排序

    struct d
    { 
        int a;
    }arr[100] 
    int cmp( const void *a ,const void *b) 
    { 
      return (*(d *)a)->a > (*(d *)b)->b ? 1 : -1; 
    } 
    qsort(arr,100,sizeof(arr[0]),cmp); 

    5、对结构体二级排序

    struct d 
    { 
        int x; 
        int y; 
    }arr[100]; 
    //按照x从小到大排序,当x相等时按照y从大到小排序 
    int cmp( const void *a , const void *b ) 
    { 
        struct d *c = (d *)a;
        struct d *e = (d *)b; 
        return c->x != e->x?c->x - e->x:return e->y - c->y; 
    } 
    qsort(d,100,sizeof(d[0]),cmp); 

    6、对字符串进行排序

    struct dict{
    char str[100]; 
    }dicts[100]
    int cmp ( const void *a , const void *b ) 
    { 
      return strcmp( (*(dict *)a)->str , (*(dict *)b)->str ); 
    } 
    qsort(dicts,100,sizeof(dicts[0]),cmp); 
  • 相关阅读:
    learnyou 相关网站
    hdu 3038 How Many Answers Are Wrong
    hdu 3047 Zjnu Stadium 并查集高级应用
    poj 1703 Find them, Catch them
    poj 1182 食物链 (带关系的并查集)
    hdu 1233 还是畅通工程
    hdu 1325 Is It A Tree?
    hdu 1856 More is better
    hdu 1272 小希的迷宫
    POJ – 2524 Ubiquitous Religions
  • 原文地址:https://www.cnblogs.com/dlvguo/p/10730062.html
Copyright © 2011-2022 走看看