C/C++教程

C++的sort函数(非原创)

本文主要是介绍C++的sort函数(非原创),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.函数介绍

使用sort函数前要提前导入c++的标准库中的algorithm库。

sort函数有三个需要输入的参数:

void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);

first:待排序数组的起始地址。

last:待排序数组的最后一个数据的下一个数据的地址。(即左闭右开)

comp:排序方法,升序或降序,默认升序。(可以自己重写该方法)

2.实例

采用默认升序方式

#include<iostream>
#include<algorithm>
using namespace std;
main()
{
  //默认采用升序排列
  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]<<" ";
}

自定义comp参数,采用降序排列方式

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int a,int 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]<<" ";
    return;
}

//自定义函数,实现降序排列
bool cmp(int a,int b){
  return a>b;
}

3.容器数据类型(还未完全理解含义)

1) 元素自身包含了比较关系,如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);
main(){
    int s[]={34,56,11,23,45};
    vector<int>arr(s,s+5);
    //注意comp参数的写法
    sort(arr.begin(),arr.end(),greater<int>());
    for(int i=0;i<arr.size();i++)
        cout<<arr[i]<<" ";
}

2)元素本身为class或者struct,类内部需要重载< 运算符,实现元素的比较;

注意事项:bool operator<(const className & rhs) const;  如果参数为引用,需要加const,这样临时变量可以赋值;重载operator<为常成员函数,可以被常变量调用; 

#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;
}

重载<也可以定义为如下格式:

struct Cmp{
    bool operator()(Info a1,Info a2) const {
        return a1.val > a2.val;
    }
};

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------转载自:https://www.cnblogs.com/junbaobei/p/10776066.html

这篇关于C++的sort函数(非原创)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!