• 转载 从最简单的vector中sort用法到自定义比较函数comp后对结构体排序的sort算法


    转载自:http://www.cnblogs.com/cj695/p/3863142.html

    sort函数在使用中非常好用,也非常简单,而且效率与冒泡或者选择排序不是一个数量级。本文就sort函数在vector中的用法分为sort函数入门用法与自定义comp比较函数比较结构体这两个最基本的功能讲讲其用法:

    1、sort入门:

    使用sort需要包含algorithm头文件,完整代码如下

    #include<iostream>
    #include<vector>
    #include<algorithm>//貌似可以不用,但最好加上。
    using namespace std;
    int main()
    {
        vector<int>v;
        v.push_back(13);
        v.push_back(23);
        v.push_back(03);
        v.push_back(233);
        v.push_back(113);
        sort(v.begin(),v.end());
        int i=0;
        for(i=0;i<5;i++)
        {
            cout<<v[i]<<endl;
        }
        return 0;
    }
    

      

    运行结果如下:

    3
    13
    23
    113
    233
    请按任意键继续. . .

    可以看到结果是从小到大排序,但如果我需要从大到小排序呢?

    2、改写comp从大到小排序。

    加入comp函数后代码如下:

    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    bool comp(const int &a,const int &b)
    {
        return a>b;
    }
    int main()
    {
        vector<int>v;
        v.push_back(13);
        v.push_back(23);
        v.push_back(03);
        v.push_back(233);
        v.push_back(113);
        sort(v.begin(),v.end(),comp);
        int i=0;
        for(i=0;i<5;i++)
        {
            cout<<v[i]<<endl;
        }
        return 0;
    }
    

      

    运行结果:

    233
    113
    23
    13
    3
    请按任意键继续. . .

    为什么会这样呢?比较时sort函数根据comp函数进行判断输的大小,系统默认a<b时返回真,于是从小到大排,而我的comp函数设定为a>b时返回为真,那么最终得到的排序结果也相应的从小到大变成从大到小。简单吧~~

    3、对结构体排序

    有了comp函数我们就可以实现对任意结构体任意对象进行排序,只需要对应修改comp函数即可实现。代码如下:

    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    struct ss
    {
        int a,b;
    };
    bool comp(const ss &a,const ss &b)
    {
        return a.a<b.a;
    }
    int main()
    {
        vector<ss>v;
        ss s1,s2,s3,s4,s5;
        s1.a=4;s1.b=23;
        s2.a=1;s2.b=213;
        s3.a=2;s3.b=231;
        s4.a=5;s4.b=123;
        s5.a=3;s5.b=223;
        v.push_back(s1);
        v.push_back(s2);
        v.push_back(s3);
        v.push_back(s4);
        v.push_back(s5);
        sort(v.begin(),v.end(),comp);
        int i=0;
        for(i=0;i<5;i++)
        {
            cout<<v[i].a<<" "<<v[i].b<<endl;
        }
        return 0;
    }
    

      

    比如ss结构体中a代表的是索引号,b代表的是索引对应的值,那么我想按索引排序,通过改写comp函数即可实现。

    结果:

    1 213
    2 231
    3 223
    4 23
    5 123
    请按任意键继续. . .

    版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
  • 相关阅读:
    Avizo
    NEWS
    HOWTO
    InstallShield 2012 Spring优惠升级到最新版本(2015.4.30之前)
    Windows系统补丁KB2962872导致InstallShield无法启动(解决方案已更新)
    HOWTO: InstallScript MSI工程取Log
    安装软件列表
    阿里云推荐码 hut29f
    ios 缺少合规证明
    ios开发错误之: Undefined symbols for architecture x86_64
  • 原文地址:https://www.cnblogs.com/radiumlrb/p/5783498.html
Copyright © 2020-2023  润新知