关于四位职工姓名排序
class date
{
int year, mouth, day;
public:
date(int year, int mouth, int day) :year(year), mouth(mouth), day(day){}
int getYear()const { return year; }
int getMouth()const{ return mouth; }
int getDay()const{ return day; }
};
class person
{
char name[14];
bool is_male;
date birth_date;
public:
person(char* name, bool is_male, date birth_date) :is_male(is_male), birth_date(birth_date)
{
strcpy(this->name, name);
}
const char* getName()const { return name; }
bool isMale()const{ return is_male; }
date getBirthDay()const { return birth_date; }
void show()
{
cout << endl;
cout << name << ","<< (is_male ? "男" : "女") << ',' << "出生日期:" << birth_date.getYear() << "年" << birth_date.getMouth() << "月" << birth_date.getDay() << "日" << endl;
}
int compareName(const person &p)const
{
return strcmp(this->name, p.name);
}
};
void sortByName(person ps[], int size)
{
for (int i = 0; i < size - 1; i++)
{
int m = i;
for (int j = i + 1; j < size;j++)
{
if (ps[j].compareName(ps[m])<0)
{
m = j;
}
if (m>i)
{
person p = ps[m];
ps[m] = ps[i];
ps[i] = p;
}
}
}
}
int _tmain()
{
person staff[] = { person ("张三",true,date(1978, 4, 20)),
person("王五",false,date(1965, 8, 3)), person("杨六",false, date(1965, 9, 5)),
person("李四",true,date(1973, 5, 30)) };
const int size = sizeof(staff) / sizeof(staff[0]);
int i;
cout << endl << "按姓名排序";
cout << endl << "排序前:";
for (i = 0; i < size;i++)
{
staff[i].show();
}
sortByName(staff, size);
cout << "排序后:"<<endl;
for (int i = 0; i < size; i++){ staff[i].show(); }
return 0;
}