結構體案例二:英雄

新鮮感~發表於2020-11-25
#include<iostream>
using namespace std;
#include<string>
//建立結構體
struct Hero {
	
	string name;
	int age;
	string sex;
};
void bubbleSort(struct Hero HeroArray[],int len) {//氣泡排序
	for (int i = 0; i < len-1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++) {
			if (HeroArray[j].age > HeroArray[j+1].age) {//陣列要傳入具體夫人變數
			struct	Hero  temp = HeroArray[j];
			HeroArray[j] = HeroArray[j + 1];
			HeroArray[j + 1] = temp;
			
			}

		}
	}
 }
void printsort(struct Hero HeroArray[],int len){ //傳入陣列-->加【】

	for (int i = 0; i < len; i++) {
		cout << "姓名: " << HeroArray[i].name << "年齡: " << HeroArray[i].age << "性別: " << HeroArray[i].sex << endl;
	}
}

int main() {

	//建立陣列存放5名英雄
	struct Hero HeroArray[3] = { {"劉備",25,"男"},{"張飛",20,"男"},{"關羽",34,"男"}, };
	//計算陣列的長度
	 int len = sizeof(HeroArray) / sizeof(HeroArray[0]);
	 //測試輸出
	 for (int i = 0; i < len; i++) {
		 cout <<"姓名: "<< HeroArray[i].name << "年齡: "<<HeroArray[i].age<<"性別: "<<HeroArray[i].sex<<endl;
	 }
	 bubbleSort(HeroArray, len);//呼叫函式,列印輸出
	 printsort(HeroArray, len);
	 return 0;
}

相關文章