1、形式:sort(first_pointer,first_pointer+n,cmp)
参数解释:
第一个参数是数组的首地址,一般写上数组名就可以,因为数组名是一个指针常量。
第二个参数相对较好理解,即首地址加上数组的长度n(代表尾地址的下一地址)。
最后一个参数是比较函数的名称(自定义函数cmp),这个比较函数可以不写,即第三个参数可以缺省,这样sort会默认按数组升序排序。
其中,自定义函数cmp:
bool cmp(int a,int b){
return a<b; //升序排列,如果改为return a>b,则为降序
}
例子:对数组A的0~n-1元素进行升序排序,只要写sort(A,A+n)即可;
2、sort扩展
①直接定义比较函数(最常用)— 结构体排序
Student Stu[100];
bool cmp(Student a,Student b)
{
return a.id>b.id;//按照学号降序排列
//return a.id<b.id;//按照学号升序排列
}
sort(Stu,Stu+100,cmp);
②使用标准库函数
在标准库中已经有现成的。是functional,我们include进来试试看。functional提供了一堆基于模板的比较函数对象,它们是:equal_to、not_equal_to、greater、greater_equal、less、less_equal。这些东西的用法看名字就知道了。在这里,我么sort要用到的也只是greater和less就足够了,用法如下:
升序:sort(begin,end,less())
降序:sort(begin,end,greater())
缺点:也只是实现简单的排序,结构体不适用。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <functional>
using namespace std;
//简单使用方法
sort(A,A+100,greater<int>());//降序排列
sort(A,A+100,less<int>());//升序排列
③重载结构体或类的比较运算符
(1)在结构体内部重载
typedef struct Student{
int id;
string name;
double grade;
bool operator<(const Student& s)
{
return id>s.id;//降序排列
//return id<s.id;//升序排列
}
};
vector<Student> V;
sort(V.begin(),V.end());
(2)在外部重载
vector<Student> V;
bool operator<(const Student& s1, const Student& s2)
{
return s1.id>s2.id;//降序排列
//return s1.id<s2.id;//升序排列
}
sort(V.begin(),V.end());
注意:一定要重载<运算符,因为系统默认是降序,用的是<运算符。
④声明比较类(少用)
struct Less
{
bool operator()(const Student& s1, const Student& s2)
{
return s1.id<s2.id; //升序排列
}
};
sort(sutVector.begin(),stuVector.end(),Less());
详见:
https://www.cnblogs.com/AlvinZH/p/6784862.html?utm_source=itdadao&utm_medium=referral