輸入若干字符串,輸出排序結果:
1. 長度短的在前。
2. 長度相同,按字符 ASCII 碼值升序(即字典序)。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const string& a, const string& b) {
if (a.length() != b.length()) return a.length() < b.length(); // 長度優先
return a < b; // 長度相同,字典序(ASCII 升序)
}
int main() {
vector list;
string s;
while (cin >> s) { // 以空白分隔讀取,遇 EOF 結束
if (s == "0") break; // 可選結束標記
list.push_back(s);
}
sort(list.begin(), list.end(), cmp);
for (const auto& str : list) cout << str << endl;
return 0;
}
std::sort 平均 O(N log N),配合嚴格弱序比較函數。cmp 必須滿足嚴格弱序:cmp(a,a)==falsecmp(a,b) && cmp(b,c) => cmp(a,c)!cmp(a,b) && !cmp(b,a) 視為等價。string 內置 operator< 按字典序比較(基於 ASCII/Unicode 碼值),直接滿足第二條件。示例中用 s == "0" 作為結束標記,實際 OJ 題目通常以 EOF 結束,直接 while(cin >> s) 即可。