sort函数

sort()

1.使用方法

头文件加上“#include ”和“using namespace std;”。
函数方式:
sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填));
不写比较函数默认对前面区间进行递增排序!
sort函数的第三个可选参数一般为compare函数(一般写做cmp函数)。

2.如何实现cmp函数?

#include <algorithm>
#include <stdio.h>
using namespace std;

bool cmp(int a, int b){
    return a>b;//可以理解为把a放到b前面
}
int main() {
    int a[] = {3,1,6,2};
    sort(a,a+4,cmp);
    for(int i=0;i<4;i++){
        printf("%d",a[i]);
    }
    return 0;
}

记忆方法:要把数据从大到小进行排序,那么就用“ > ”,因为“a > b”就是左大右小。要把数据从小到大,就是“ < ”,因为“a < b”,左小右大。不确定的时候,随便先试试就知道应该用哪种的了!

3.容器的排序

在STL标准容器中,只有vector、string、deque可以使用sort函数。因为如set、map这种容器使用红黑树实现的,元素本身有序,所以不允许使用sort函数!
以vector容器为例子:

#include <algorithm>
#include <stdio.h>
#include <vector>
using namespace std;

bool cmp(int a, int b){
    return a < b;
}
int main() {
    vector<int> v;
    v.push_back(3);
    v.push_back(7);
    v.push_back(1);
    sort(v.begin(),v.end(),cmp);
    for(int i=0;i<3;i++){
        printf("%d",v[i]);
    }
    return 0;
}

补充1:

用sort函数对结构体数据进行排序。
结构体如下:

struct node{
    int x,y;
}student[maxn];

如果想要先按照x的值从大到小进行排序,但如果遇到x相等的情况,就按照y的大小从小到大进行排序,此时的cmp函数如何写呢?

bool cmp(node a, node b){
    if(a.x != b.x)    return a.x > b.x;
    else return a.y < b.y;
}

补充2:

strcmp函数。
strcmp函数是string.h头文件下用来比较两个char型数组的字典序大小的,其中strcmp(str1,str2)当str1的字典序小于str2时返回一个负数,相等时返回零,大于时返回一个正数。所以会出现下面的写法:

bool cmp(Student a,Student b){
    if(a.score != b.score)  return a.score > b.score;
    else  return strcmp(a.name,b.name)<0;
}

上面的cmp函数的写法应该会经常用到,因此单独拿出来说!

原文地址:https://www.cnblogs.com/techgy/p/15021807.html