zoukankan      html  css  js  c++  java
  • C++中 sort() 函数使用方法

    1. 基本性质

      sort函数包含在头文件为#include<algorithm>的c++标准库中,调用标准库里的排序方法可以实现对数据的排序,但是sort函数是如何实现的,我们不用考虑!

    2. sort函数参数

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

    (1)第一个参数first:是要排序的数组的起始地址。

    (2)第二个参数last:是结束的地址(最后一个数据的后一个数据的地址)

    (3)第三个参数comp是排序的方法:可以是从升序也可是降序。如果第三个参数不写,则默认的排序方法是从小到大排序。

    3. 实例运行

    (1) 自定义sort函数的第三个参数

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 bool cmp(int a,int b);
     5 int main(){
     6   //sort函数第三个参数自己定义,实现从大到小
     7   int a[]={45,12,34,77,90,11,2,4,5,55};
     8   sort(a,a+10,cmp);
     9   for(int i=0;i<10;i++)
    10     cout<<a[i]<<" ";
    11 }
    12 //自定义函数
    13 bool cmp(int a,int b){
    14   return a>b;
    15 }

    (2)对于容器,容器中的数据类型可以多样化

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

     1 class student{
     2     char  name[20];
     3     int math;
     4     int english;
     5 }Student;
     6 bool cmp(Student a,Student b);
     7 int main(){
     8     int s[]={34,56,11,23,45};
     9     vector<int>arr(s,s+5);
    10     sort(arr.begin(),arr.end(),greater<int>());
    11     for(int i=0;i<arr.size();i++)
    12         cout<<arr[i]<<" ";
    13 }

      b. 元素本身为class类型,类内部需要重载 < 运算符,实现元素的比较;

     1 class student{
     2     char  name[20];
     3     int math;
     4     //按math从大到小排序
     5     inline bool operator < (const student &x) const {
     6         return math>x.math ;
     7     }
     8 }Student;
     9 int main(){
    10     Student a[4]={{"apple",67},{"limei",90},{"apple",90}};
    11     sort(a,a+3);
    12     for(int i=0;i<3;i++)
    13         cout<<a[i].name <<" "<<a[i].math <<" " <<endl;
    14 }

    注意:sort() 为全局函数,需要将引用的第三个参数设置为静态 static 或 const才可以调用。

  • 相关阅读:
    网络数据处理
    进程间通信和网络
    附加的操作系统服务
    通用操作系统服务
    UIScrollView 子控件的自动布局经验
    UIImage 添加水印
    数据类型
    ios 获取手机的IP地址
    UILAbel 设置了attributedText 后省略号不显示
    swift
  • 原文地址:https://www.cnblogs.com/john1015/p/13027152.html
Copyright © 2011-2022 走看看