這次的題目是http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?a=18031
同時也是ITSA第52次的題目
題目最主要就是要練習能夠以布林函數來設定排序的條件
- #include <iostream>
- #include <string.h>
- #include <sstream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- bool f(string a,string b);
- int main()
- {
- int num;
- cin>>num;
- cin.get();
- for(int i=0;i<num;i++)
- {
- string input;
- getline(cin,input);
- istringstream delim(input);
- string token;
- vector<string>arr;
- while(getline(delim,token,' '))
- {
- arr.push_back(token);
- }
- sort(arr.begin(),arr.end(),f);
- for(int j=0;j<arr.size();j++)
- {
- if(j!=arr.size()-1)
- cout<<arr[j]<<" ";
- else
- cout<<arr[j]<<endl;
- }
- }
- return 0;
- }
- bool f(string a,string b)
- {
- if(a[0]>b[0])
- return true;
- else if(a[0]==b[0])
- {
- if(a.length()>b.length())
- return true;
- else if(a.length()==b.length() && a.length()==2)
- {
- if(a[1]>b[1])
- return true;
- else
- return false;
- }
- else if(a.length()==b.length() && a.length()==3)
- {
- if(a[2]>b[2])
- return true;
- else
- return false;
- }
- else
- return false;
- }
- else
- return false;
- }
先寫好布林函數,並在裡面寫按照甚麼樣的條件排序
再把函數放在sort後面,這樣就可以照著函數所寫的條件,來排序sort裡放的陣列了
至於函數裡的程式碼,在否的時後return false,我原本是沒有打,但這樣上傳是錯的
題目似乎是要求要打上才會給對,所以一般來講不打程式也會執行出對的答案
若想閱讀相關文章請關注我的粉絲團
小資菜鳥向前衝
文章標籤
全站熱搜
留言列表