這次的題目是http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?a=18031

同時也是ITSA第52次的題目

題目最主要就是要練習能夠以布林函數來設定排序的條件

  1. #include <iostream>  
  2. #include <string.h>  
  3. #include <sstream>  
  4. #include <vector>  
  5. #include <algorithm>  
  6. using namespace std;  
  7. bool f(string a,string b);  
  8. int main()  
  9. {  
  10.     int num;  
  11.     cin>>num;  
  12.     cin.get();  
  13.     for(int i=0;i<num;i++)  
  14.     {  
  15.         string input;  
  16.         getline(cin,input);  
  17.         istringstream delim(input);  
  18.         string token;  
  19.         vector<string>arr;  
  20.         while(getline(delim,token,' '))  
  21.         {  
  22.             arr.push_back(token);  
  23.         }  
  24.         sort(arr.begin(),arr.end(),f);  
  25.         for(int j=0;j<arr.size();j++)  
  26.         {  
  27.             if(j!=arr.size()-1)  
  28.                 cout<<arr[j]<<" ";  
  29.             else  
  30.                 cout<<arr[j]<<endl;  
  31.         }  
  32.     }  
  33.     return 0;  
  34. }  
  35. bool f(string a,string b)  
  36. {  
  37.     if(a[0]>b[0])  
  38.         return true;  
  39.     else if(a[0]==b[0])  
  40.     {  
  41.         if(a.length()>b.length())  
  42.             return true;  
  43.         else if(a.length()==b.length() && a.length()==2)  
  44.         {  
  45.             if(a[1]>b[1])  
  46.                 return true;  
  47.             else  
  48.                 return false;  
  49.         }  
  50.         else if(a.length()==b.length() && a.length()==3)  
  51.         {  
  52.             if(a[2]>b[2])  
  53.                 return true;  
  54.             else  
  55.                 return false;  
  56.         }  
  57.         else  
  58.             return false;  
  59.     }  
  60.     else  
  61.         return false;  
  62. }  

先寫好布林函數,並在裡面寫按照甚麼樣的條件排序

再把函數放在sort後面,這樣就可以照著函數所寫的條件,來排序sort裡放的陣列了

至於函數裡的程式碼,在否的時後return false,我原本是沒有打,但這樣上傳是錯的

題目似乎是要求要打上才會給對,所以一般來講不打程式也會執行出對的答案

若想閱讀相關文章請關注我的粉絲團

小資菜鳥向前衝

https://www.facebook.com/%E5%B0%8F%E8%B3%87%E8%8F%9C%E9%B3%A5%E5%90%91%E5%89%8D%E8%A1%9D-204484273323335/?fref=ts

arrow
arrow
    文章標籤
    程式設計 題目介紹
    全站熱搜

    cychss6305 發表在 痞客邦 留言(0) 人氣()