C++ 中sort 函数及 cmp 自定义规则的使用

需要头文件

#include<algorithm>

using namespace std;

这个函数可以传两个参数或三个参数。第一个参数是要排序的区间首地址,第二个参数是区间尾地址的下一地址。也就是说,排序的区间是[a,b)。简单来说,有一个数组int a[100],要对从a[0]到a[99]的元素进行排序,只要写sort(a,a+100)就行了,默认的排序方式是升序。

需要对数组t的第0到len-1的元素排序,就写sort(t,t+len);对向量v排序也差不多,sort(v.begin(),v.end());

排序的数据类型不局限于整数,只要是定义了小于运算的类型都可以,比如字符串类string。

 如果是没有定义小于运算的数据类型,或者想改变排序的顺序,就要用到第三参数——比较函数。

比较函数是一个自己定义的函数,返回值是bool型,它规定了什么样的关系才是“小于”。想把刚才的整数数组按降序排列,可以先定义一个比较函数cmp
bool cmp(int a,int b)
{
 return a>b;
}
 排序的时候就写sort(a,a+100,cmp);

假设自己定义了一个结构体node
struct node{
 int a;
 int b;
 double c;
}
 有一个node类型的数组node arr[100],想对它进行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写这样一个比较函数:
以下是代码片段:
bool cmp(node x,node y)
{
 if(x.a!=y.a) return x.a

if(x.b!=y.b) return x.b>y.b;
 return return x.c>y.c;
} 排序时写sort(arr,a+100,cmp);



例题:
题目来源:http://ac.jobdu.com/problem.php?pid=1061
对于sort 以及 cmp的使用暂未有较深了解,后续补充

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;
struct student
{
    int grade;
    char name[101];
    int age;
}stu[1001];
bool cmp(student a,student b)//定义比较规则 
{
    int temp = strcmp(a.name,b.name);
    if(a.grade!=b.grade) 
        return a.grade<b.grade; //升序
    else if(temp != 0)//升序 ,要做是否相等的判断 
        return temp<0; //此处一定要用 TEMP < 0 返回,否侧会出错,原因未知 
    else
        return a.age < b.age;//升序

}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
        scanf("%s%d%d",&stu[i].name , &stu[i].age,&stu[i].grade);
        sort(stu,stu+n,cmp);
        for(int i=0;i<n;i++)
            printf("%s %d %d\n",stu[i].name , stu[i].age,stu[i].grade);
    }
    return  0;
}

猜你喜欢

转载自blog.csdn.net/u010112268/article/details/81258671