STL sort函数的用法

sort在STL库中是排序函数,有时冒泡、选择等O(N^2)算法会超时时,我们可以使用STL中的快速排序O(N log N)完成排序

sort在<algorithm>库里面,原型如下:

template <class RandomAccessIterator>
 void sort ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class Compare>
 void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

他有两种形式一个有三个参数,一个有两个参数,我们先讲讲两个参数的吧!

sort的前两个参数是起始地址和中止地址

如:sort(a,a+n) 表示对a[0] a[1] a[2] ... a[n-1] 排序

代码如下:

#include <algorithm>
#include <cstdio>
using namespace std;
int main() {
    int n,a[1001];
    scanf("%d",&n);  //输入有多少个数
    for (int i = 1;i <= n;i++) scanf("%d",&a[i]);  //输入这个数列
    sort(a+1,a+n+1);  //对a[1] a[2] a[3] ... a[n] 排序
    for (int i = 1;i <= n;i++) printf("%d",a[i]);  //输出
    return 0'
}

这样是默认升序的,那如果是降序呢?

这样,我们就要用到第三个参数,第三个参数是一个比较函数

bool cmp(int a,int b) {
    return a > b;
}

这个就是降序排序的比较函数,意思:

是a > b时为true,就不交换,a < b时为false,交换

然后我们调用sort(a+1,a+n+1,cmp);就可以对a[1] a[2] a[3] ... a[n] 进行排序了

sort也能对结构体排序,如:

#include <algorithm>
#include <cstdio>
using namespace std;
struct Node {
    int x,y;
}p[1001];
int n;
bool cmp(Node a,Node b) {
    if (a.x != b.x) return a.x < b.x;  //如果a.x不等于b.x,就按x从小到大排
    return a.y < b.y;  //如果x相等按y从小到大排
}
int main() {
    scanf("%d",&n);
    for (int i = 1;i <= n;i++) scanf("%d%d",&p[i].x,&p[i].y);
    sort(p+1,p+n+1,cmp);
    for (int i = 1;i <= n;i++) scanf("%d %d\n",p[i].x,p[i].y);
    return 0;
}

以上代码的意思是,如果a.x不等于b.x,就按x从小到大排;如果x相等按y从小到大排

结构体还可以重载运算符,使sort只用两个参数就可以按自己的规则排序,如:

#include <algorithm>
#include <cstdio>
using namespace std;
struct Node {
    int x,y;
    bool operator < (Node cmp) const {
        if (a.x != cmp.x) return a.x < cmp.x;
        return a.y < cmp.y;
    }
}p[1001];
int n;
//bool cmp(Node a,Node b) {
//    if (a.x != b.x) return a.x < b.x;  //如果a.x不等于b.x,就按x从小到大排
//    return a.y < b.y;  //如果x相等按y从小到大排
//}
int main() {
    scanf("%d",&n);
    for (int i = 1;i <= n;i++) scanf("%d%d",&p[i].x,&p[i].y);
    sort(p+1,p+n+1);
    for (int i = 1;i <= n;i++) scanf("%d %d\n",p[i].x,p[i].y);
    return 0;
}

 

转载于:https://www.cnblogs.com/lrj124/p/7254043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值