zoukankan      html  css  js  c++  java
  • 今日份sort“行为大赏”

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

    sort函数的参数:

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

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

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

    一、只进行初始的从大到小的数字排序

    #include<bits/stdc++.h>
    using namespace std;
    int main(){
        int n,a[501];
        cin>>n;
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        sort(a,a+n);
        for(int i=0;i<n;i++) cout<<a[i]<<" ";
        return 0;
    }

    二、加入第三个参数,实现特殊排序

    (1)实现从大到小

    #include<bits/stdc++.h>
    using namespace std;
    bool cmp(int a,int b){
        return a>b;
    }
    int main(){
        int n,a[501];
        cin>>n;
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        sort(a,a+n,cmp);
        for(int i=0;i<n;i++) cout<<a[i]<<" ";
        return 0;
    }

    (2)字典序+大到小/小到大

    #include<bits/stdc++.h>
    using namespace std;
    struct xs{
        string xm;
        int fs;
    }a[25];
    int n;
    bool cmp(xs x,xs y){
        if(x.fs==y.fs) return x.xm<y.xm;
        else return x.fs>y.fs;
    }
    int main(){
        cin>>n;
        for(int i=0;i<n;i++)
            cin>>a[i].xm>>a[i].fs;
        sort(a,a+n,cmp);
        for(int i=0;i<n;i++) cout<<a[i].xm<<" "<<a[i].fs<<endl;
        return 0;
    } 
    //题目链接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1178

    推荐题目:http://ybt.ssoier.cn:8088/problem_show.php?pid=1177

         http://ybt.ssoier.cn:8088/problem_show.php?pid=1179

  • 相关阅读:
    MARKY一下。
    从一个git仓库拷贝到另一个git仓库
    Git:四、连接GitHub远程仓库
    木门工厂木门、门套、套线公式和算法
    设计模式之代理模式
    2018年软件开发状态报告
    产品研发流程与周期(非原创)
    软件工程师的核心竞争力
    linux下安装redis安装使用
    8 个 Tips 让你更好的进行 Code Review
  • 原文地址:https://www.cnblogs.com/qwn34/p/14043834.html
Copyright © 2011-2022 走看看