sort排序

    sort排序是将数组进行升序或降序排序,比冒泡排序快,sort默认是升序排序,并且使用时需加入头文件algorithm。

 例如对一个数组升序排序:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int a[5]={23,56,89,66,78},i;
    sort(a,a+5);
    for(i=0;i<5;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    return 0;
}

输出:

sort(数组名,数组名+总元素个数);

如果需要降序排序,则需要加上一个比较函数,如:

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(const int a,const int b)
{
    return(a>b);//'>'为降序排序,'<'为升序
}
int main()
{
    int a[5]={23,56,89,66,78},i;
    sort(a,a+5,cmp);
    for(i=0;i<5;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    return 0;
}

    使用sort对结构体排序:

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
typedef struct
{
    string name;
    int num;
    int score;
}Student;
bool cmp(const Student a,const Student b)
{
    return(a.score<b.score);//对成绩进行比较 
}
int main()
{
    Student s[10];
    int i;
    for(i=0;i<5;i++)
        cin>>s[i].name>>s[i].num>>s[i].score;
    sort(s,s+5,cmp);//对结构体进行排序
    for(i=0;i<5;i++)
        cout<<s[i].name<<" "<<s[i].num<<" "<<s[i].score<<endl;
    return 0;
}

输入:

输出:

总的来说,定义一个函数对结构体中元素进行比较,在将该函数放入sort中即可。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值