C++的Sort函数使用方法


sort函数知识储备

sort函数包含在头文件#include<algorithm>的C++标准库的中,我们不需要考虑实现

sort函数有三个参数

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
  1. first:是要排序的数组的起始地址。
  2. last:是结束的地址 (最后一个数据的后一个数据的地址)
  3. comp:是排序的方法,可以是从升序也可是降序。不写,默认的排序方法是从小到大排序。

实例

默认排序

#include<iostream>
#include<algorithm>

using namespace std;

int main(){
    // sort函数第三个参数采用默认从小到大
    int a[]={45,12,34,77,90,11,2,4,5,55};
    sort(a,a+10); 
    for(int i=0;i<10;i++){
        cout<<a[i]<<" ";
    }
}

运行结果

自定义之从大到小排序

#include<iostream>
#include<algorithm>

using namespace std;

bool cmp(int a,int b){
    return a>b;
}

int main(){
    // sort函数第三个参数自定义,实现从大到小 
    int a[]={45,12,34,77,90,11,2,4,5,55};
    sort(a,a+10,cmp);
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
}

运行结果

自定义之结构体排序

#include<iostream>
#include<algorithm>

using namespace std;

typedef struct student{
    char name[20];
    int math;
    int english; 
}Student;

bool cmp(Student a, Student b){
    if(a.math>b.math){
        return a.math<b.math;            // 按math从小到大排序 
    } else if(a.math==b.math){
        return a.english>b.english;     // math相等,按english从大到小排序 
    }
} ;

int main() {
    // 先按math从小到大排序,math相等,按english从大到小排序
    Student a[4]={{"apple",67,89},{"limei",90,56},{"apple",90,99}} ;
    sort(a,a+3,cmp);
    for(int i=0;i<3;i++)
        cout<<a[i].name<<" "<<a[i].math<<" "<<a[i].english<<endl; 
}

运行结果

自定义之容器多样化排序对比

元素自身包含了比较关系,如int,double等基础类型,可以直接进行比较greater<int>() 递减, less<int>() 递增(省略)

#include<iostream>
#include<algorithm>

#include<vector>

using namespace std;
typedef struct student{
    char name[20];
    int math;
    int english;
}Student;

bool cmp(Student a,Student b);

int main(){
    int s[]={34,56,11,23,45};
    vector<int> arr(s,s+5);
    sort(arr.begin(),arr.end(),greater<int>());
    for(int i=0;i<arr.size();i++)
        cout<<arr[i]<<" ";
}

运行结果

自定义之元素本身含排序函数

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

typedef struct student{
    char name[20];
    int math;
    // 按math从大到小排序
    inline bool operator<(const student& x) const{
        return math>x.math; 
    } 
}Student;

int main(){
    Student a[4]={{"apple",67},{"limei",90},{"apple",90}};\
    sort(a,a+3);
    for(int i=0;i<3;i++){
        cout<<a[i].name<<" "<<a[i].math<<" "<<endl;
    }
} 

运行结果

参考

https://www.cnblogs.com/junbaobei/p/10776066.html C++中sort函数使用方法
https://blog.csdn.net/github_34965845/article/details/80540013 C++泛型基础


文章作者: Jelly
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jelly !
  目录