排序题与sort()函数
如何使用
sor()的使用必须加上头文件#include和using namespace std;
其使用方式如下:
sort(首元素地址(必填),尾元素下个地址(必填),比较函数(非必填));
如果不写比较函数,将默认对前面给出的区间进行递增排序
示例:
#include<iostream>
#include<algorithm>
int main()
{
using namespace std;
int a[5]={1,9,13,2,0};
sort(a,a+4);
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";//将对前四个元素进行递增排序
}
}
同理可对double型,char型(默认为字典顺序)进行排序
如何实现比较函数cmp
int,double,char
如果想要从小到大排序,可以这样定义cmp
bool cmp(int x,int y)
{
return x>y;
}
#include<iostream>
#include<algorithm>
bool cmp(int x,int y)
{
return x>y;
}
int main()
{
using namespace std;
int a[5]={1,9,13,2,0};
sort(a,a+4,cmp);
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
}
即可实现递减排序
double,char同理,只需修改cmp的形参
结构体数组
现在定义了如下结构体
struct node{
int x,y;
}ssd[10];
我们想将ssd数组按x从大到小,只需要
bool cmp(node a,node b){
return a.x>b.x;
}
容器的排序
STL标准容器中,只有vector,string,deque可以使用
#include<iostream>
#include<algorithm>
#include<vector>
bool cmp(int x,int y)
{
return x<y;
}
int main()
{
using namespace std;
vector<int> a;
a.push_back(1);
a.push_back(3);
a.push_back(2);
sort(a.begin(),a.end(),cmp);
for(int i=0;i<3;i++)
{
cout<<a[i]<<" ";
}
}
再看string的排序(按字典序)
#include<iostream>
#include<algorithm>
#include<string>
int main()
{
using namespace std;
string str[3]={"bbb","aaaaa","ccc"};
sort(str,str+3);
for(int i=0;i<3;i++)
{
cout<<str[i]<<endl;
}
}
如果想按照字符串的长度从小到大排序,则可以这样:
#include<iostream>
#include<algorithm>
#include<string>
bool cmp(std::string str1,std::string str2)
{
return str1.length()>str2.length();
}
int main()
{
using namespace std;
string str[3]={"bbb","aaaaa","ccc"};
sort(str,str+3);
for(int i=0;i<3;i++)
{
cout<<str[i]<<endl;
}
}