用C++编写程序输入5个英文人名,对人名进行排序输出(字典序,升序)。
时间: 2024-03-06 21:51:18 浏览: 23
好的,我可以帮你解决这个问题。
你可以使用C++中的STL库中的sort函数来排序。以下是一个简单的程序实现:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string names[5];
cout << "请输入5个英文人名:" << endl;
for(int i = 0; i < 5; i++) {
cin >> names[i];
}
sort(names, names + 5); // 对数组进行排序
cout << "排序后的人名为:" << endl;
for(int i = 0; i < 5; i++) {
cout << names[i] << endl;
}
return 0;
}
```
在这个程序中,我们首先定义一个长度为5的字符串数组用来存储输入的5个人名。然后使用for循环遍历数组,通过cin输入每一个人名。
接着,我们使用STL库中的sort函数对数组进行排序。sort函数的第一个参数是要排序的数组的起始地址,第二个参数是要排序的数组的终止地址。这里我们使用了数组名+数组长度的方式来指定终止地址。
最后,使用for循环遍历排序后的数组,输出排序后的人名。
注意,这里的排序是按照字典序升序排序的。如果需要降序排序,可以在sort函数中加入greater<string>(),如下所示:
```cpp
sort(names, names + 5, greater<string>());
```
希望能帮到你!