qsort/sort函数之cmp

C语言

void qsort(   待排序数组首地址 ,   数组中待排序元素数量 ,   各元素的占用空间大小   ,  cmp(const void*,const void*)  );

头文件: #include<stdlib.h>

C++

void sort(   待排序数组首地址  ,  数组首地址+数组长度  , cmp  );

头文件: #include<algorithm>

一般类型

1.qsort

cmp函数原理(以int类型为例):

bool cmp(const void *a,const void *b )

{
    return *(int *)a-*(int *b);    //降序排列
   //等同于 return *(int *)a>*(int *b);
}

当函数返回值>0      a 排在 b 前

当函数返回值<0      b 排在 a 前
 

int,char ,double 等简单类型的

bool cmp(const void *a,const void *b )

{
    return *(int *)a-*(int *b);    //降序排列
    /********
    (int *)为强制类型转换
    根据需要改写
    *********/
    
}

2.sort

bool cmp( int &a ,int &b)
{
    return a>b;
}

/*char double float...也可以*/

结构体类型

1.sort 

一级结构体

struct node{
    int x;
    char y;

//方法一:
    bool operator <(const node &a)    //运算符重载
    {
        return x>a.x;    //降序排列
    }
    
//方法二:
    bool operator <(const node &a, const node &b)
    {
        return a.y>b.y;
    }
};


vector<node> v;

sort( v.begin(),v.end() );

//方法三
    bool cmp(node &a,node &b)
    {
        return a.x>b.x;
    }
vector<node> v;

sort( v.begin(),v.end(),cmp );

 二级结构体

struct node 
{
    int num;   
    int id;
};

bool cmp(node &a,node &b)
{
    if(a.num!=b.num)
        return a.num>b.num;    //num大的在前
    else
        return a.id<b.id;      //num相同的,id小的在前
}

sort( ,  , cmp );

2.qsort 

struct node{
	int id;
	int flag;
	int pos;
};


//一级结构体比较
bool cmp1(const void *a,const void *b)
{
	return (*(struct node *)a).pos>(*(struct node *)b).pos?1:0;  //从小到大排序 
}



int cmp2(const void *a,const void *b)
{
	return (*(struct node *)a).id-(*(struct node *)b).id;
}


//二级结构体比较

int cmp1(const void *a,const void *b)
{
    if((*(struct node *)a).pos!=(*(struct node *)b).pos)
	    return (*(struct node *)a).pos-(*(struct node *)b).pos;		//从小到大排序 
    else
        return  (*(struct node *)a).id-(*(struct node *)b).id;      //pos 相等的 比较 id
}

3.sort 和 qsort 皆可

可以直接调用库函数    #include<functional>

equal_to

实现x == y的函数对象 
(类模板)

not_equal_to

实现x != y的函数对象 
(类模板)

greater

实现x > y的函数对象 
(类模板)

less

实现x < y的函数对象 
(类模板)

greater_equal

实现x >= y的函数对象 
(类模板)

less_equal

实现x <= y的函数对象 
(类模板)

字符串类型的

struct node {
char str[100];
int num;
};

int cmp1(const void *a, const void *b)
{
    return strcmp((struct node *)a->str,(struct node *)b->str;
}

qsort( , , , cmp);

  若c++中为string 类型数据则直接使用大于小于即可

猜你喜欢

转载自blog.csdn.net/qq_42026596/article/details/82385317