zoukankan      html  css  js  c++  java
  • STL sort 的用法

    sort的原型:

    default (1)    
    template <class RandomAccessIterator>
      void sort (RandomAccessIterator first, RandomAccessIterator last);
    custom (2)    
    template <class RandomAccessIterator, class Compare>
      void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

     说明:

    1、排序的区间可以是数组下标或者迭代器,如果是迭代器必须是随机迭代器(如vector支持的迭代器和自己定义的支持随机迭代器的数据结构)
    2、默认情况下是采用从小到大的方式排列的
    3、STL内部提供了less<T>() 、greater<T>(),以及自定义的数据结构:
    string a[]={"1","3","2"};
    vector<string> b(a,a+3);
        sort(b.begin(),b.end());
    //sort(b.begin(),b.end(),less<string>()); the same

    定义排序函数:

    方法1:声明外部比较函数

    bool Less(const Student& s1, const Student& s2)
    {
        return s1.name < s2.name; //从小到大排序
    }
    std::sort(sutVector.begin(), stuVector.end(), Less);

    注意:比较函数必须写在类外部(全局区域)或声明为静态函数

    当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。

    否则,会出现错误

    class Leg
    {
    public:
        int length;
        int cost;
        Leg(int x,int y):length(x),cost(y){}
        bool operator < (const Leg& a) const //不加const会报错的
        {
           return length<a.length;
        }
        bool operator=(const Leg& a)const
        {
            return length==a.length;
        }
    };

    方法2:重载类的比较运算符

    bool operator<(const Student& s1, const Student& s2)
    {
        return s1.name < s2.name; //从小到大排序
    }
    std::sort(sutVector.begin(), stuVector.end());

    方法3:声明比较类

    struct Less
    {
        bool operator()(const Student& s1, const Student& s2)
        {
            return s1.name < s2.name; //从小到大排序
        }
    };
    
    std::sort(sutVector.begin(), stuVector.end(), Less());
  • 相关阅读:
    linux内核(四)内存管理单元MMU
    open函数详解
    linux内核(三)文件系统
    C++中数字与字符串之间的转换 scanf string总结(复习必读)
    hello程序的运行过程-从计算机系统角度
    剑指offer第12题打印从1到n位数以及大整数加法乘法
    2017-10-11第二次万革始面经
    为什么需要半关闭
    Ubuntu指令
    143. Reorder List
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/5381883.html
Copyright © 2011-2022 走看看