PTA 英文单词排序 (25分)
本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。
输入格式:
输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。
输出格式:
输出为排序后的结果,每个单词后面都额外输出一个空格。
输入样例:
blue
red
yellow
green
purple
#
输出样例:
red blue green yellow purple
#include <iostream>
#include <algorithm>
using namespace std;
struct Str {
string s;
int n;
bool operator<(const Str& a) {
if (s.size() == a.s.size())
return n < a.n;
return s.size() < a.s.size();
}
};
int main() {
int cnt = 0;
string a;
Str str[20];
while (cin >> a && a != "#")
str[cnt].s = a, str[cnt].n = cnt++;
sort(str, str + cnt);
for (int i = 0; i < cnt; ++i)
cout << str[i].s << " ";
return 0;
}
22分代码(测试点3未过):原因sort排序不稳定,不能保证长度相同,按照输入的顺序排序
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int cnt = 0;
string c, a[25];
while (cin >> c && c != "#")
a[cnt++] = c;
sort(a, a + cnt, [](const auto& a, const auto& b) { return a.size() < b.size(); });
for (int i = 0; i < cnt; ++i)
cout << a[i] << " ";
return 0;
}
版权声明:本文为qq_45798109原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。