关于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;
}
}