实现:结构体案例

案例1描述:

学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下

设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员

学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值

最终打印出老师数据以及老师所带的学生数据。

#include<iostream>
#include<string>
#include<ctime>
using namespace std;


struct student {
	string name;
	int score;
};

struct teacher {
	string name;
	struct student stu[5];
};

void to_catch(struct teacher t[], int len) {
	string nameSeed = "ABCDE";
	for (int i = 0; i < len; i++) {
		t[i].name = "Teacher_";
		t[i].name += nameSeed[i];
		for (int j = 0; j < 5; j++) {
			t[i].stu[j].name = "student_";
			t[i].stu[j].name += nameSeed[j];
			t[i].stu[j].score = rand() % 61 + 40;
		}
	}
}

void to_print(struct teacher t[],int len) {
	for (int i = 0; i < len; i++) {
		cout << "老师的名称为 " << t[i].name << endl;
		for (int j = 0; j < 5; j++) {
			cout << "	学生的名称为 " << t[i].stu[j].name << " 成绩为 " << t[i].stu[j].score << endl;

		}
	}
}


int main() {

	srand((unsigned)(time(NULL)));
	struct teacher t[3];
	int len = sizeof(t) / sizeof(teacher);
	//cout << len << endl;

	to_catch(t, len);
	to_print(t, len);

	system("pause");
	return 0;
}

案例2描述:
设计一个英雄的结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名英雄。

通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果。

五名英雄信息如下:

		{"刘备",23,"男"},
		{"关羽",22,"男"},
		{"张飞",20,"男"},
		{"赵云",21,"男"},
		{"貂蝉",19,"女"},
#include<iostream>
#include<string>
#include<ctime>
using namespace std;


struct hero {
	string name;
	int age;
	string sex;
};

void to_bubble(struct hero h[], int len) {
	struct hero temp;
	for (int i = 0; i <len-1 ; i++) {
		for (int j = i + 1; j < len; j++) {
			if (h[i].age < h[j].age) {
				temp = h[i];
				h[i] = h[j];
				h[j] = temp;
			}
		}
		
	}

}

void to_print(struct hero h[], int len) {
	for (int i = 0; i < len; i++) {
		cout << h[i].name << "," << h[i].age << endl;
	}
}

int main() {
	struct hero h[5] = {
		{"刘备",23,"男"},
		{"关羽",22,"男"},
		{"张飞",20,"男"},
		{"赵云",21,"男"},
		{"貂蝉",19,"女"},
	};

	struct hero temp;
	int len = sizeof(h) / sizeof(hero);
	to_bubble(h, len);
	to_print(h, len);
	system("pause");
	return 0;
}

原文地址:https://www.cnblogs.com/zpchcbd/p/11844670.html