sort函数使用总结

在官方定义中,sort函数有三个参数

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp)

分别是

first:是要排序的数组的起始地址。

last:是结束的地址(最后一个数据的后一个数据的地址)

comp是排序的方法:可以是从升序也可是降序。如果第三个参数不写,则默认的排序方法是从小到大排序。

 

当我们不使用comp时,sort函数默认为升序处理。常用sort(shuzu.begin(),shuzu.end())

当排序数组时,如果有定长度要求,可设置为sort(shuzu,shuzu+3)

定义comp方法:

comp是bool型的,有两个数据接口,我们这里设置为a、b

一般情况下:

 bool cmp(Student a,Student b){
  if(a.math >b.math )
  return a.math <b.math ;}

我们可以简单认为输入到comp的两者a、b在经过函数体处理后,如果返回true,返回a值,false返回b值。全部元素可认为是comp迭代产生。

容器中:

一、容器有很多关系,直接进行比较greater<int>() 递减, less<int>() 递增

用法:

sort(arr.begin(),arr.end(),greater<int>());

二、或者元素本身为class或者struct,类内部需要重载< 运算符,实现元素的比较;

注意事项:bool operator<(const className & rhs) const;  如何参数为引用,需要加const,这样临时变量可以赋值;重载operator<为常成员函数,可以被常变量调用; 

 1 #include<iostream>
 2 #include<algorithm>
 3 #include"vector"
 4 using namespace std;
 5 typedef struct student{
 6     char  name[20];
 7     int math;
 8     //按math从大到小排序 
 9     inline bool operator < (const student &x) const {
10         return math>x.math ;
11     }
12 }Student;
13 main(){
14     Student a[4]={{"apple",67},{"limei",90},{"apple",90}};
15     sort(a,a+3);
16     for(int i=0;i<3;i++)    
17         cout<<a[i].name <<" "<<a[i].math <<" " <<endl;     
18 }

如下也可以:

1 struct Cmp{
2     bool operator()(Info a1,Info a2) const {//其中())为重载的符号
3     return a1.val > a2.val;
4     }
5 };

看看这位博主的,讲的更细致icon-default.png?t=M85Bhttps://blog.csdn.net/qq_46527915/article/details/114597901

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值