Chapter 07 Structure Practice Questions for Introduction to C++

1. Design a hero structure, including name, age, and gender; create a structure array and store 5 heroes in the array; use the bubble sorting algorithm to sort the heroes in the array in ascending order according to age, and finally print the sorted the result of.

#include <iostream>
using namespace std;

//设计一个英雄的结构体
struct  Hero
{
	string name;
	int age;
	string sex;
};

//通过冒泡排序进行升序排序
void BubbleSort(struct Hero hero[], int len) {
	for (int i = 0; i < len; i++)
	{
		for (int j = 0; j < len - 1; j++)
		{
			if (hero[i].age < hero[j].age)
			{
				Hero temp = hero[i];
				hero[i] = hero[j];
				hero[j] = temp;
			}
		}
	}
}

int main()
{
	//创建结构体数组
	Hero hero[] =
	{
		{ "刘备",23,"男" },
		{ "关羽",22,"男" },
		{ "张飞",20,"男" },
		{ "赵云",21,"男" },
		{ "貂蝉",19,"女" }
	};

	//取得数组长度
	int len = sizeof(hero) / sizeof(hero[0]);

	BubbleSort(hero, len);
	

	//打印排序后的结果
	for (int i = 0; i < len; i++)
	{
		cout << hero[i].name << "\t" << hero[i].age << "\t" << hero[i].sex << "\t" << endl;
	}
}

Guess you like

Origin blog.csdn.net/qq_43036676/article/details/100543854