为实现按“赵、钱、孙、李”顺序排序,可将这四个姓氏对应4个从小到大的整数,将输入的姓名中的姓查找到其对应的整数,按照这个整数进行排序;当该数相同时,再比较名进行
#include #include
#include
#include
using namespace std;
string first_name[]={"赵","钱","孙","李"};
struct node
{
int 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;
}
bool cmp(const node &a, const node &b)
{
if (a.name.substr(0, 2) == b.name.substr(0, 2))
return a.name < b.name;
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<<"输入多少个姓名?"<<ENDL;
cin>>n;
cout<<"请输入"<<N<<"个姓名"<<ENDL;
/*读入数据 赵钱孙李姓氏的,设置id为0,1,2,3*/
for (i = 0; i < n; ++i) {
cin>>str;
names[i].name = str;
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[I].NAME<<" "<<NAMES[I].ID<<ENDL;*
/*排序*/
sort(names, names + n, cmp);
for (i = 0; i < n; ++i)
cout<<NAMES[I].NAME<<ENDL;
return 0;
}
绿色部分看不懂??谁来解释一下??