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

前端之家收集整理的这篇文章主要介绍了算法学习 - STL的p排序函数(sort)使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的PHP相关文章