正在阅读:
- 首页 » 开发运维 » AI编程C++,按姓氏笔画排序...
AI编程C++,按姓氏笔画排序...
题目描述
召开会议时,我们经常看到“按姓氏笔画排序”。现在,我们来做一个按姓名拼音顺序(字典顺序)排序。输入多人的姓名进行比较,按从小到大的顺序输出。
输入格式
第一行输入人数 n。
第二行起 n 行,每行为英文单词或中文拼音(字符串)。
如第一行输入一个数字5
第二行开始,每行输入一个拼音或者单词如:
mouse
elephant
cat
dog
bird
输出格式:
1 bird
2 cat
3 dog
4 elephant
5 mouse
编程:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
// 自定义比较函数,用于比较姓名拼音的字典顺序
bool compareByName(const std::string& name1, const std::string& name2) {
return name1 < name2; // 使用默认的字典顺序比较
}
int main() {
int n;
std::cout << "请输入人数: ";
std::cin >> n;
std::vector<std::string> names(n);
for (int i = 0; i < n; ++i) {
std::cout << "请输入第 " << i + 1 << " 个人的姓名拼音: ";
std::cin >> names[i];
}
// 使用sort函数和自定义的比较函数对姓名进行排序
std::sort(names.begin(), names.end(), compareByName);
std::cout << "按姓名拼音排序结果:" << std::endl;
for (int i = 0; i < n; ++i) {
std::cout << i + 1 << ". " << names[i] << std::endl;
}
return 0;
}
该日志由 bemender 于 2024年05月10日 发表
转载请注明文本地址:http://www.bemhome.com/post/198.html