sort
功能:用于排序,复杂度为O(N*log(N))。
1 使用方法
1 sort (a+m,a+n);//()[a+m,a+n)范围内的元素进行排序
2 sort (a+m,a+n,cmp);//cmp是函数或仿函数
2 含义解释:
a+m相当于a[m];
cmp是函数或者仿函数
3 头文件
#include <algorithm>
4 使用
#include <iostream>
#include <algorithm>
using namespace std;
int a[100] = {5,1,8,4,2,5,7,4,9,10};//定义需要排序的数组中的前十个数
int main()
{
sort(a+0,a+10);//数组名+数字的本质是指针操作,a+0可以用a替代
for(int i=0;i<10;i++)
cout<<a[i]<<" ";//输出排序后的数组,查看结果
return 0;
}
注:使用sort默认从小到大排序
如何从大到小排序
#include <iostream>
#include <algorithm>
using namespace std;
int a[100] = {5,1,8,4,2,5,7,4,9,10};//定义需要排序的数组
bool mycmp(int a,int b)
{
if(a>b)
return 1;
return 0;
}
int main()
{
sort(a+0,a+10,mycmp);//数组名+数字的本质是指针操作
for(int i=0;i<10;i++)
cout<<a[i]<<" ";//输出排序后的数组
return 0;
}
根据返回结果来确定顺序
原理:当函数返回true的时候,会把第一个元素放到前面,从而实现把大的元素放在左边。
仿函数问题
c++分别内置了两个比较大小的仿函数less和greater分别进行大小的比较,
#include <iostream>
#include <algorithm>
using namespace std;
int a[100] = {5,1,8,4,2,5,7,4,9,10};//定义需要排序的数组
int main()
{
sort(a+0,a+10,greater<int> ());//数组名+数字的本质是指针操作
for(int i=0;i<10;i++)
cout<<a[i]<<" ";//输出排序后的数组
return 0;
}
greater的原理:
#include <iostream>
#include <algorithm>
using namespace std;
int a[100] = {5,1,8,4,2,5,7,4,9,10};//定义需要排序的数组
struct big{//理解成定义greater的过程
bool operator()(int a,int b){
return a>b;
}
};
int main()
{
sort(a+0,a+10,big());
for(int i=0;i<10;i++)
cout<<a[i]<<" ";//输出排序后的数组
return 0;
}
对结构体进行排序(结构体不能直接比较大小)
方法
1.cmp
定义仿函数时接收的两个参数定义为结构体
2.重载小于号
原因:结构体不能直接比较大小
使用方法
#include <iostream>
#include <algorithm>
using namespace std;
struct node{//定义结构体
int a,b;
//重载小于号过程
bool operator<(node B){
if(a!=B.a)return a<B.a;
return b<B.a;
}
};
int main()
{
node a[10]={//给结构体里的两个参数赋值
{2,3},
{10,10},
{5,5},
{4,4},
{10,4},
{7,1},
{10,10},
{4,6},
{10,7},
{2,8},
};
sort(a+0,a+10);//排序
for(int i=0;i<10;i++)//输出排序结果
cout<<a[i].a<<" "<<a[i].b<<endl;
return 0;
}
如果只排序两个元素,可以使用pair(本质也是结构体排序)
3.仿函数,与cmp的用法相同
以上是sort的用法,如有错误,望大佬指正