struct Exam {
string name; //名前
int tall; //身長
int weight; //体重
};
const int MAX = 5; //構造体配列要素数
//健康クラス定義
class Health {
Exam exam[MAX]; //検診構造体配列
public:
//検診設定 ex[]:検診構造体配列
void setExam(Exam ex[])
{
for (int i = 0; i < MAX; i++)
{
exam[i].name = ex[i].name;
exam[i].tall = ex[i].tall;
exam[i].weight = ex[i].weight;
}
}
//検診ソート
void sortExam()
{
string n;
int t;
int w;
for (int i = 0; i < (MAX - 1); i++)
{
for (int j = (i + 1); j < MAX; j++)
{
if (exam[j].tall > exam[i].tall)
{
n = exam[i].name;
t = exam[i].tall;
w = exam[i].weight;
exam[i].name = exam[j].name;
exam[i].tall = exam[j].tall;
exam[i].weight = exam[j].weight;
exam[j].name = n;
exam[j].tall = t;
exam[j].weight = w;
}
else if (exam[j].tall == exam[i].tall)
{
if (exam[j].weight > exam[i].weight)
{
n = exam[i].name;
t = exam[i].tall;
w = exam[i].weight;
exam[i].name = exam[j].name;
exam[i].tall = exam[j].tall;
exam[i].weight = exam[j].weight;
exam[j].name = n;
exam[j].tall = t;
exam[j].weight = w;
}
}
}
}
}
//検診表示
void show()
{
for (int i = 0; i < MAX; i++)
{
cout << exam[i].name << " " << exam[i].tall << " " << exam[i].weight << endl;
}
}
};
////////////////////////////////////////////////////////////
int main()
{
Health health; //healthオブジェクト
//検診構造体配列宣言
Exam exam[MAX] = {
{ "GUNMO", 160, 80 },
{ "BERZEB", 80, 30 },
{ "HARY", 170, 70 },
{ "TRINITY", 160, 50 },
{ "ROBO", 170, 90 }
};
health.setExam(exam); //検診設定メソッド呼び出し
health.show(); //ソート前(検診表示)メソッド呼び出し
health.sortExam(); //ソートメソッド呼び出し
cout << endl;
health.show(); //ソート後(検診表示)メソッド呼び出し
_getch();
return 0;
}
我把整段代码都复制过来了,数组排序的时候是先按照身高的降顺,如果身高一样则按体重的降顺,我只会这么写,是不是应该有稍微简单的写法呢?