c++/sort函数的使用

关于sort函数的使用场景有很多,下面主要总结常用的几种.

需要头文件<algorithm>

语法描述:sort(begin,end,cmp),cmp参数可以没有,如果没有默认非降序排序。

1.以int为例的基本数据类型的sort使用

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()//默认升序
{
    int a[5]={1,3,4,2,5};
    sort(a,a+5);
    for(int i=0;i<5;i++)
        cout<<a[i]<<' ';
    return 0;
}

若设计为非升序排序,则cmp函数的编写:

bool cmp(int a,int b)

{return a>b;}

2.char型数组处理字符串的排序

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

bool cmp(char a,char b)
{
    return a>b;//降序 
}

int main()
{
    char s[10]="asdfgh";
	sort(s,s+strlen(s));//默认升序 
	cout<<s<<endl;
	return 0;
}

3.对字符串string类型排序

Ex古老的密码(Ancient Cipher,NEERC 2004,UVa1339)

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//不是AC代码
int main()
{
	string s="JWPUDJSTVP";
	sort(s.begin(),s.end());
	cout<<s<<endl;
	
	string s1="WJDUPSJPVT";
	sort(s1.begin(),s1.end());
	
	cout<<s1<<endl;
	return 0;
}
使用反向迭代器可以完成逆序排序sort(s.rbegin(),s.rend());

4.以结构体为例的一,二级排序

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person
{
    string name;
    int    high;
};
bool cmp(Person p1,Person p2)
{
     if(p1.high>p2.high)//一级排序
     {
        return true;
     }
     else
     {
        if(p1.high==p2.high)
        {
            if(p1.name<p2.name)//二级排序
			return true;
            else
            return false;
        }
        else
        return false;   
     }
}
 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值