C++ sort()排序

头文件:

在C++中使用sort()函数需要使用#include<algorithm>头文件。

参数:

sort(begin, end, cmp)

begin:为指向待sort()的数组的第一个元素的指针

end:为指向待sort()的数组的最后一个元素的下一个位置的指针

cmp:排序准则,cmp参数可以不写,如果不写的话,默认升序排序;也可以将cmp参数写为greater<int>()

使用标准库函数:

sort(A,A+100,greater<int>());//降序排列
sort(A,A+100,less<int>());//升序排列

如:equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
  int num[6]={0,3,4,5,1,2};
  sort(num,num+6,greater<int>());
  for(int i=0;i<6;i++)
  {
    cout<<num[i]<<" ";
  //输出5 4 3 2 1 0
  }
}

自定义排序:

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int x,int y)
{
  return x % 10 >y % 10;
}//按照个位的降序

int main()
{
  int num[5]={90,33,28,39,76};
  sort(num,num+5,cmp);
  for(int i=0;i<5;i++)
  {
    cout<<num[i]<<" ";
  }//39 28 76 33 90

}

结构体排序:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

struct Student{
  string name;
  int score;
  Student(){};
  Student(string n,int s):name(n),score(s){}
};

bool cmp_score(Student x,Student y)
{
  return x.score>y.score;
}

int main()
{
  Student stu[3];
  string n;
  int s;
  for(int i=0;i<3;i++)
  {
    cin>>n>>s;
    stu[i]=Student(n,s);
  }
  sort(stu,stu+3,cmp_score);
  for(int i=0;i<3;i++)
  {
    cout<<stu[i].name<<" "<<stu[i].score<<endl;
  }
}
//输入
小金 12
小米 23
小王 33
//输出
小王 33
小米 23
小金 12

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

beiqianqian

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值