sort的用法:
MSDN中的定义:
template<'class RanIt>
void sort(RanIt first, RanIt last); //–> 1)
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr); //–> 2)
头文件:
#include “algorithm”
using namespace std;
说明:sort有默认的比较函数,默认是按升序排列。
void sort(RanIt first, RanIt last, Pred pr);前两个参数为迭代器指针,分别指向容器的首尾,第三个参数为比较方法。
比较方法有三种:
1、默认(不写):对于内置类型,按照升序排列;
2、标准库自带函数:functional提供了一堆基于模板的比较函数对象:equal_to、not_equal_to、greater、greater_equal、less、less_equal。升序:sort(begin,end,less()); 降序:sort(begin,end,greater()).
3、自定义函数:如
int cmp(const int &a,const int &b)
{
return a>b
}
Sort中的cmp函数参数可以直接是参与比较的引用类型。
sort中cmp函数的自定义规则
作者:淼淼1111
来源:优快云
原文:https://blog.youkuaiyun.com/u010112268/article/details/81258671
需要头文件
#include
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
#include<string.h>
#include
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;}