华中科技大学复试 最长&最短文本
题目描述
输入多行字符串,请按照原文本中的顺序输出其中最短和最长的字符串,如果最短和最长的字符串不止一个,请全部输出。
输入描述
输入包括多行字符串,字符串的长度len(1<=len<=1000)。
输出描述
按照原文本中的顺序输出其中最短和最长的字符串,如果最短和最长的字符串不止一个,请全部输出。
示例
输入
hello
she
sorry
he
输出
he
hello
sorry
总结
本题的关键是,如何接受多个串,前提是串的数目,我们是不知道的。代码区的while语句块,是本题的关键。
Code
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool comp(string a, string b)
{
return a.length() < b.length();
}
int main()
{
vector<string> a;
string str;
while (getline(cin, str))
{
a.push_back(str);
}
sort(a.begin(), a.end(), comp);
int min_lenth = a[0].length();
int max_lenth = a[a.size() -1].length();
for (int i = 0; i < a.size(); i++)
if (a[i].length() == min_lenth)
cout << a[i] << endl;
for (int i = 0; i < a.size(); i++)
if (a[i].length() == max_lenth)
cout << a[i] << endl;
return 0;
}