算法學習 - STL的p排序函數(sort)使用
來源:程序員人生 發布時間:2015-01-05 07:56:46 閱讀次數:3452次
排序函數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 給的輸入格式。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈