C++ sort函数的使用

总述

sort函数是c++STL中的很常用的算法
sort函数不是简单的快速排序,而是结合了其他排序算法,根据数据量动态选择合适的算法
故而在算法竞赛中,我们时常不需要手写排序,直接使用STL的sort函数就好了

举个栗子

直接举个例子,能更加直接的学习

#include<iostream>
#include<algorithm>//sort函数包含于算法库内
using namespace std;
//比较函数,用于升序排序
bool cmp(int a,int b){
    return a>b;
}

int arr[]={3,2,5,4};
int main(){
sort(arr,arr+4);
for(int i=0;i<=3;i++) cout<<arr[i]<<endl;
//默认升序排序
cout<<"-------------------"<<endl;
sort(arr,arr+4,cmp);
for(int i=0;i<=3;i++) cout<<arr[i]<<endl;
}
//利用cmp函数降序排序

浅讲一下

使用sort函数需要 #include<algorithm>
传两个参数的话,默认升序
sort(arr,arr+4);
传三个参数,第三个参数为一个bool函数,这大大提高了sort函数的灵活性
sort(arr,arr+4,cmp);

posted @ 2022-08-11 10:00  加零lan  阅读(72)  评论(0编辑  收藏  举报