返回列表 發帖

自定排序 (二)

設計一個程式,讓使用者任意輸入5個只包含數字的字串,運用自定排序的技巧,讓這些字串依其數字的總合遞增排序。

  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<algorithm>
  4. using namespace std;
  5. bool compare(string a, string b)
  6. {
  7.     int sa=0, la=a.length();
  8.     int sb=0, lb=b.length();
  9.     for(int i=0; i<la; i++)
  10.         sa+=a[i]-'0';
  11.     for(int i=0; i<lb; i++)
  12.         sb+=b[i]-'0';
  13.     return sa<sb;
  14. }
  15. int main()
  16. {
  17.     string n[5];      //宣告一個大小為5的空陣列
  18.     cout<<"請任意輸入5個只包含數字的字串:"<<endl;
  19.     for(int i=0; i<5; i++)
  20.         cin>>n[i];
  21.     sort(n, n+5, compare);
  22.     cout<<"排序結果(依數字的總合):"<<endl;
  23.     for(string s: n)
  24.         cout<<s<<endl;
  25.     system("pause");
  26.     return 0;
  27. }
複製代碼

返回列表