如何用C++实现对姓名按拼音排序

来源:百度知道 编辑:UC知道 时间:2024/06/14 10:16:54
只要随便输入姓名就可以实现按照字典顺序排列所输入姓名,这个程序不知道给从哪里入手,望大家帮帮忙!

这里的要点在ASCII值,每个字母都有对应的ASCII值,所以只需比较姓名的ASCII值就可以了(如果按照abc的顺序排列就是按照ASCII值从小到大排列),
#include <string.h>
#include <iostream.h>
void main()
{

char str[4][10]={"ccc","aaa","bbb","ddd"};//定义四个字符串
char *p[4];
for(int y=0;y<4;y++)
{
p[y]=str[y];
}
for(int i=0;i<3;i++)
{
for(int j=i+1;j<4;j++)
{
char temp[10];
if(*p[i]>*p[j])//比较str[i]和str[j]的ASCII值大小
{
temp[10]=*p[i];//将str[i]赋给temp[10]
*p[i]=*p[j];
*p[j]=temp[10];
}
}

}
for(int k=0;k<4;k++)
cout<<str[k]<<endl;
}

如果直接用标准库就简单了

string str;
vector<string > vstr;
cin>>str;
vstr.push_back(str);

//排序
sort(vstr.begin(), vstr.end());

直接用strcmp函数就行了