加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 20:24:34 所属栏目:PHP教程 来源:网络整理
导读:排序函数sort() 这个函数是STL自带的,功能很强大~ 这里教下使用方法。 sort()有3个参数,第1个是排序的起始位置,第2个是排序的结束位置,第3个是排序的判断函数。函数原型为: sort(#_RandomAccessIterator __first#,#_RandomAccessIterator __last#,#_Com

排序函数sort()

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

使用方法

首先假定我们有1个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()⑴) { printf(" "); }else{ printf(" "); } } } return 0; }

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读