再次相遇sort, 再次的感悟
以前本人曾經在CSDN上面發表過一篇關于sort的用法的文章。
現在摘錄如下:
sort 函數是經常要用到的高級函數,用到好處,你會感覺你真的很棒!
但是,第一個問題就是,你十分了解sort函數嗎?其實不然。
如果你就不徹底了解它,怎能用好呢?現在讓我小露一手吧!
我們可以自定義sort函數呢,當然,它要和結構體共同使用,那樣更爽,
它的這個功能主要用在多級排序上,方便死了。
例如:
struct student
{
char name;
int x, y, z;
}stu[1000];
bool check(strdent a, student b)
{
if(a.x > b.x)return true;
if(a.x == b.x && a.y > b.y) return true;
return false;
}
int main()
{
int n;
cin>>n;
for(int i=0; i<n; i++)
cin>>stu[i].name>>stu[i].x>>stu[i].y>>stu[i].z;
sort(stu, stu+n, check)
.........
}
怎么樣,有點收獲吧。
當然,我所知道是有限的,不可能很全面,還望高手指點幾招。
然而,今天又做了一個題目,又遇到了新的問題,下面做出說明。
題目是這樣的:
Sample Input
5
ab
gdh
c
gaa
caa
Sample Output
c ab caa gaa gdh
ab c caa gaa gdh
顯然,這個是一個十分簡單的題目,用上面的方法,立即
就可以解決,但是要說明的是,當你自定義了一個Check
函數以后,就不能用sort原來自身的比較功能。要想用的
話,必須再次定義一下。不然,連編譯都通不過。
下面貼出我的樣例代碼(是通過了的)
#include "iostream"
#include "string"
#include "cstring"
#include "algorithm"
using namespace std;
struct str
{
string substr;
}allstr[1001];
bool Check(str s1, str s2) //這個就是用來解決第一種排序了
{
if(s1.substr.length() < s2.substr.length()) return true;
if(s1.substr.length()==s2.substr.length() && s1.substr.compare(s2.substr)<0) return true;
return false;
}
bool Check1(str s1, str s2) //這個就是sort函數自身所帶有功能,但是,在這里還要重新定義一下,不然不可用
{
if(s1.substr.compare(s2.substr) < 0) return true;
return false;
}
int main()
{
int Case;
cin>>Case;
for(int i=0; i<Case; i++)
cin>>allstr[i].substr;
sort(allstr, allstr+Case, Check);
for(int i=0; i<Case-1; i++)
cout<<allstr[i].substr<<" ";
cout<<allstr[Case-1].substr<<endl;
sort(allstr, allstr+Case, Check1);
for(int i=0; i<Case-1; i++)
cout<<allstr[i].substr<<" ";
cout<<allstr[Case-1].substr<<endl;
}
posted on 2011-10-21 10:36 More study needed. 閱讀(446) 評論(0) 收藏 舉報
浙公網安備 33010602011771號