C++百家姓排序简化程序,只对百家姓的前四个姓“赵、钱、孙、李”进行排序。输入20个人的姓名,他们的姓为

2025-03-10 06:45:32
推荐回答(1个)
回答1:

#include
#include
#include
#include
using namespace std;

string first_name[]={"赵","钱","孙","李"};

struct node
{
int id;//姓氏id,以方便利用此进行姓氏排序
string name;//姓名
void operator = (const node &a);//操作符重载,这里也没用到,所以下面的也不用说了。
node():id(0),name(""){};
};

void node::operator =(const node &a)
{
this->id = a.id;
this->name = a.name;
}

//这是sort函数用到的比较函数cmp,如果a < b则返回真,否则返回假,sort函数就是
//根据这个来进行排序的。
bool cmp(const node &a, const node &b)
{
//如果姓氏相同,进行名的比较
if (a.name.substr(0, 2) == b.name.substr(0, 2))
return a.name < b.name;

//否则利用id比较哪个姓氏靠前
else
return a.id < b.id;
}

int main()
{
//freopen("d:\\1.txt", "r",stdin);
size_t n, i;
int id;
string str;
node names[30];

cout<<"输入多少个姓名?"< cin>>n;
cout<<"请输入"<
//先进行输入操作,这个不用解释吧。
for (i = 0; i < n; ++i) {
cin>>str;
names[i].name = str;

//根据姓氏给id赋值
for (id = 0; id < 4; ++id) {
if (first_name[id] == str.substr(0, 2)) {
names[i].id = id;
}
}
}

/*for (i = 0; i < n; ++i)
cout<
//对names数组按照比较函数cmp进行排序,这也就是最主要的一步
sort(names, names + n, cmp);

//输出排序结果
for (i = 0; i < n; ++i)
cout<
return 0;
}