算法學(xué)習(xí) - STL的p排序函數(shù)(sort)使用
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-01-05 07:56:46 閱讀次數(shù):3463次
排序函數(shù)sort()
這個(gè)函數(shù)是STL自帶的,功能很強(qiáng)大~ 這里教下使用方法。
sort()有3個(gè)參數(shù),第1個(gè)是排序的起始位置,第2個(gè)是排序的結(jié)束位置,第3個(gè)是排序的判斷函數(shù)。函數(shù)原型為:
sort(<#_RandomAccessIterator __first#>, <#_RandomAccessIterator
__last#>, <#_Compare __comp#>)
這個(gè)就是原型了~
使用方法
首先假定我們有1個(gè)vector<int> vec;
向量容器,寄存了很多無(wú)序正數(shù),那末我們就開(kāi)始用sort給這些整數(shù)排序。首先其實(shí)位置是:vec.begin()
結(jié)束位置是:vec.end()
,比較函數(shù)可以不寫,默許是升序。也能夠手寫。
代碼實(shí)現(xiàn)
直接看代碼實(shí)現(xiàn)會(huì)很簡(jiǎn)單~
//
// 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;
}
這就是個(gè)實(shí)現(xiàn)代碼了~測(cè)試?yán)诱?qǐng)看:
http://acm.hdu.edu.cn/showproblem.php?pid=1040 給的輸入格式。
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)