这个不是偶写地,在网上看到,给楼主参考:
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
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;
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;
}
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
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;
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;
}