本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。
输入格式:
输入为若干英文单词,每行一个,以#
作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。
输出格式:
输出为排序后的结果,每个单词后面都额外输出一个空格。
输入样例:
blue
red
yellow
green
purple
#
输出样例:
red blue green yellow purple
注意:再用sort排序时一定要用结构体或数组把输入顺序储存起来,不然sort会在数据较多的时候把原有的输入顺序打乱
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
struct Word{
string s;
int num;
}w[21];
bool cmp(Word x, Word y ) {
if ( x.s.length()!=y.s.length() )
return x.s.length()<y.s.length();
else
return x.num<y.num;
}
int main(void)
{
int cnt = 0;
while ( cin >> w[cnt].s && w[cnt].s!="#" ) w[cnt].num=cnt, cnt ++;
sort(w, w+cnt, cmp);
for ( int i=0; i<cnt; i++ ) {
cout << w[i].s << " ";
}
return 0;
}