算法学习 - STL的排序函数(sort)使用

排序函数sort()

这个函数是STL自带的,功能很强大~ 这里教下使用方法。
sort()有三个参数,第一个是排序的起始位置,第二个是排序的结束位置,第三个是排序的判断函数。函数原型为:
sort(<#_RandomAccessIterator __first#>, <#_RandomAccessIterator __last#>, <#_Compare __comp#>)
这个就是原型了~

使用方法

首先假设我们有一个vector<int> vec;向量容器,存放了很多无序正数,那么我们就开始用sort给这些整数排序。首先其实位置是:vec.begin()结束位置是:vec.end(),比较函数可以不写,默认是升序。也可以手写。

代码实现

直接看代码实现会很简单~

//
//  main.cpp
//  hdu_1040
//
//  Created by Alps on 15/1/3.
//  Copyright (c) 2015年 chen. All rights reserved.
//
//http://acm.hdu.edu.cn/showproblem.php?pid=1040

#include <iostream>
#include <vector>
using namespace std;

bool sortRule(int a, int b){
    return a < b;
}

int main(int argc, const char * argv[]) {
    int n;
    scanf("%d",&n);
    int num;
    int a = 0;
    for (int i = 0; i < n; i++) {
        scanf("%d",&num);
        vector<int> list;
        while (num--) {
            scanf("%d",&a);
            list.push_back(a);
        }
        sort(list.begin(), list.end(), sortRule);
        vector<int>::iterator iter;
        for (iter = list.begin(); iter != list.end(); iter++) {
            printf("%d",*iter);
            if (iter == list.end()-1) {
                printf("\n");
            }else{
                printf(" ");
            }
        }
    }
    return 0;
}

这就是个实现代码了~测试例子请看:

http://acm.hdu.edu.cn/showproblem.php?pid=1040 给的输入格式。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值