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());
原文地址:https://www.cnblogs.com/daocaorenblog/p/5381883.html