国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 算法学习 - STL的p排序函数(sort)使用

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

来源:程序员人生   发布时间:2015-01-05 07:56:46 阅读次数:3240次

排序函数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 给的输入格式。

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生