c++,用vector对英文名字进行排序 输入5个英文人名,对人名进行排序输出(字典序,升序)。
时间: 2024-03-02 08:50:08 浏览: 23
好的,以下是使用 `vector` 实现该功能的 C++ 代码:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main() {
const int n = 5;
vector<string> names(n);
// 输入人名
cout << "请输入" << n << "个英文人名:" << endl;
for (int i = 0; i < n; i++) {
getline(cin, names[i]);
}
// 按字典序排序
sort(names.begin(), names.end());
// 输出排序结果
cout << "排序后的结果为:" << endl;
for (int i = 0; i < n; i++) {
cout << names[i] << endl;
}
return 0;
}
```
代码中,我们使用 `vector<string>` 来存储输入的人名,通过循环和 `getline` 函数实现输入,`sort` 函数实现按字典序排序,最后通过循环输出排序结果。需要注意的是,对于 `vector`,我们需要使用 `begin()` 和 `end()` 函数表示其首尾迭代器。
相关问题
c++对英文名字进行排序 输入5个英文人名,对人名进行排序输出(字典序,升序)。
好的,以下是实现该功能的 C++ 代码:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
const int n = 5;
string names[n];
// 输入人名
cout << "请输入" << n << "个英文人名:" << endl;
for (int i = 0; i < n; i++) {
getline(cin, names[i]);
}
// 按字典序排序
sort(names, names + n);
// 输出排序结果
cout << "排序后的结果为:" << endl;
for (int i = 0; i < n; i++) {
cout << names[i] << endl;
}
return 0;
}
```
代码中,我们首先定义了一个长度为 5 的字符串数组 `names` 来存储输入的人名。然后通过循环和 `getline` 函数来实现输入,`sort` 函数实现按字典序排序,最后通过循环输出排序结果。
用C++编写程序输入5个英文人名,对人名进行排序输出(字典序,升序)。
好的,我可以帮你解决这个问题。
你可以使用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>());
```
希望能帮到你!