sort函数的使用
1、调用的库:#include<algorithm>
2、模板:sort(first_pointer,first_pointer+n,cmp)
第一个参数:数组的首地址
第二个参数:结束地址
第三个参数:设置sort的排序方法,默认为升序排序
代码示例:
1 #include<iostream> 2 #include<algorithm>//调用sort函数所需的库 3 using namespace std; 4 int main() 5 { 6 int a[]={1,2,3,10,9,5,6,8,7};//数组长度为9 7 sort(a,a+9); 8 for(int x:a) 9 { 10 cout<<x<<" ";//遍历数组,查看输出的结果 11 } 12 }
运行结果:

如果要将输出的结果改为降序,则需要自己定义cmp方法:
1 #include<iostream> 2 #include<algorithm>//调用sort函数所需的库 3 using namespace std; 4 bool cmp(int a,int b) 5 { 6 return a>b; 7 }//重新定义cmp方法 8 int main() 9 { 10 int a[]={1,2,3,10,9,5,6,8,7};//数组长度为9 11 sort(a,a+9,cmp); 12 for(int x:a) 13 { 14 cout<<x<<" ";//遍历数组,查看输出的结果 15 } 16 }
运行结果:

sort函数的第三个参数的方法名一般使用cmp来命名,用户也可根据自己的编码习惯命名

浙公网安备 33010602011771号