C++对一个中文姓名数组按照姓氏的第一个字母排序
时间: 2025-07-05 16:11:22 浏览: 5
### C++ 中实现按照中文姓名姓氏首字母排序
对于C++中处理包含中文姓名的数组并依据姓氏的第一个字母进行排序,可以采取以下方式:
#### 使用自定义比较函数
为了能够根据特定需求对字符串进行排序,在C++标准库中的`std::sort()`提供了接受自定义比较器的能力。这使得可以通过编写一个专门用于提取汉字拼音首字母作为关键字来进行对比的方法。
由于直接获取汉字对应的拼音较为复杂,通常会借助第三方库如[PinyinHelper](https://github.com/mozillazg/pinyin),但在本场景下只需关注第一个字符即可简化操作。下面是一个简单的例子展示如何基于此逻辑完成任务[^1]。
```cpp
#include <algorithm>
#include <iostream>
#include <vector>
// 获取Unicode编码下的汉语拼音首字母(仅适用于单个汉字)
char getFirstLetterOfPinyin(unsigned int unicodeChar){
static const std::pair<unsigned int, char> table[]={
{0xb0c5,'a'},{0xb2c1,'b'},{0xb4ed,'c'},
{0xb6e9,'d'},{0xb7a2,'e'},{0xb8c1,'f'},
{0xb9fe,'g'},{0xbbf7,'h'},{0xc0ab,'j'},
{0xc2e7,'k'},{0xc4c3,'l'},{0xc5b6,'m'},
{0xc5bd,'n'},{0xd1b9,'o'},{0xd4d0,'p'},
{0xd7fa,'q'},{0xdaaf,'r'},{0xe0ac,'s'},
{0xe3e7,'t'},{0xe5e6,'w'},{0xe7a1,'x'},
{0xeaa0,'y'},{0xf470,'z'}
};
auto it = std::lower_bound(std::begin(table), std::end(table)-1,
std::make_pair(unicodeChar,'\0'),
[](const decltype(*table)::first_type& p1,
const decltype(*table)& p2){return p1<p2.first;});
return (it != std::end(table)) ? (*it).second : '\0';
}
bool compareBySurname(const std::wstring &name1, const std::wstring &name2){
unsigned int firstCharCodeName1 = name1[0];
unsigned int firstCharCodeName2 = name2[0];
char letter1 = getFirstLetterOfPinyin(firstCharCodeName1);
char letter2 = getFirstLetterOfPinyin(firstCharCodeName2);
if(letter1 == letter2)// 如果两个名字的首字母相同,则继续比较后面的字
return name1 < name2;
return letter1 < letter2;
}
int main(){
std::vector<std::wstring> names={L"李华", L"张三", L"王五", L"赵六"};
std::wcout.imbue(std::locale(""));
// 输出原始顺序
for(auto&& n : names)
wcout << n << endl;
// 对names向量调用sort算法,并传入compareBySurname作为第三个参数
std::sort(names.begin(), names.end(), compareBySurname);
// 打印已排序后的结果
wcout << L"\n排序后:" << endl;
for(auto&& n : names)
wcout << n << endl;
return 0;
}
```
这段代码实现了对中国人的常见姓氏按拼音首字母从小到大排序的功能。注意这里的`getFirstLetterOfPinyin`函数只是一个非常粗略的模拟版本,实际项目可能需要更精确的方式获得每个汉字的确切拼音信息[^2]。
阅读全文