. C++题目52:按名字长度对英文名字进行排序 输入5个英文人名,对人名进行排序输出(名字长度,如果长度相同,按照字典序,升序)。
时间: 2024-03-18 22:42:23 浏览: 35
好的,这是一个简单的排序题目,可以使用C++的STL库中的sort函数来实现。以下是示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string a, string b) {
if (a.length() == b.length()) {
return a < b;
}
return a.length() < b.length();
}
int main() {
string names[5];
for (int i = 0; i < 5; i++) {
cin >> names[i];
}
sort(names, names + 5, cmp);
for (int i = 0; i < 5; i++) {
cout << names[i] << endl;
}
return 0;
}
```
在这个程序中,我们首先定义了一个名为`cmp`的比较函数,用于排序时比较两个字符串的长度和字典序。然后我们使用一个`for`循环来读入5个英文人名,并使用`sort`函数对这5个人名进行排序。最后我们再使用一个`for`循环输出排序后的结果。
希望这个答案能够帮到你!
相关问题
C++题目52:按名字长度对英文名字进行排序 输入5个英文人名,对人名进行排序输出(名字长度,如果长度相同,按照字典序,升序)。 【输入形式】 5个英文人名 【输出形式】 排序后的人名 【样例输入】 Bob Candy Andy Elle David 【样例输出】 Bob Andy Elle Candy David
好的,这是一个比较常见的排序问题。下面是C++程序的实现:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool cmp(string a, string b) // 自定义比较函数
{
if(a.size() == b.size()) // 如果名字长度相同
{
return a < b; // 按字典序升序排序
}
else
{
return a.size() < b.size(); // 按名字长度升序排序
}
}
int main()
{
string names[5]; // 存储5个英文人名
cout << "请输入5个英文人名:" << endl;
for(int i = 0; i < 5; i++)
{
cin >> names[i];
}
sort(names, names + 5, cmp); // 对人名进行排序
cout << "排序后的人名为:" << endl;
for(int i = 0; i < 5; i++)
{
cout << names[i] << " ";
}
cout << endl;
return 0;
}
```
输入样例:
```
Bob Candy Andy Elle David
```
输出样例:
```
排序后的人名为:
Bob Andy Elle Candy David
```
希望能够帮到你!
用C++编程:输入5个英文人名,对人名进行排序输出(名字长度,如果长度相同,按照字典序,升序)。
非常好,请看下面的 C++ 代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string names[5];
cout << "请输入5个英文人名,用空格隔开:";
for (int i = 0; i < 5; i++) {
cin >> names[i];
}
// 使用冒泡排序对人名进行排序
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4-i; j++) {
if (names[j].length() > names[j+1].length() || (names[j].length() == names[j+1].length() && names[j] > names[j+1])) {
swap(names[j], names[j+1]);
}
}
}
cout << "排序后的人名为:";
for (int i = 0; i < 5; i++) {
cout << names[i] << " ";
}
cout << endl;
return 0;
}
```
您可以尝试输入一组数据进行测试,比如输入:Tom Jerry Mary John Alice。代码将对这些人名进行排序输出,结果为:Alice John Mary Tom Jerry。