结构体例题

1.

 

 

复制代码
 1 #include <iostream>
 2 #include <string>
 3 
 4 const int Slong = 5;
 5 using namespace std;
 6 
 7 struct student{
 8     string sname;
 9     int score;
10 };
11 
12 struct teacher{
13     string tname;
14     struct student sArr[Slong];
15 };
16 
17 void fuzhi(struct teacher tArr[], int tlen){
18     string nameSeed = "ABCDE";
19     for (int i = 0; i < tlen; i++){
20         tArr[i].tname = "Teacher_";
21         tArr[i].tname += nameSeed[i];
22 
23         for (int j = 0; j < Slong; j++){
24             tArr[i].sArr[j].sname = "Student_";
25             tArr[i].sArr[j].sname += nameSeed[j];
26 
27             tArr[i].sArr[j].score = 60;
28         }
29     }
30 }
31 
32 void printInfo(struct teacher tArr[], int tlen){
33     for (int i = 0; i < tlen; i++){
34         cout << "老师名字:" << tArr[i].tname << endl;
35 
36         for (int j = 0; j < Slong; j++){
37 
38             cout << "\t学生名字:" << tArr[i].sArr[j].sname <<"学生成绩:" << tArr[i].sArr[j].score << endl;
39         }
40     }
41 }
42 
43 int main(){
44     struct teacher tArr[3];
45     int tlen = sizeof(tArr) / sizeof(tArr[0]);
46     fuzhi(tArr,tlen);
47     printInfo(tArr,tlen);
48     system("pause");
49     return 0;
50 }
复制代码

2.

 

 

 

 

复制代码
 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 struct Hero{
 7     string name;
 8     int age;
 9     string sex;
10 };
11 
12 //冒泡排序
13 void bubbleSort(struct Hero hArr[], int len){
14     for (int i = 0; i < len - 1; i++){
15         for (int j = 0; j < len - i - 1; j++){
16             if (hArr[j].age > hArr[j+1].age){
17                 struct Hero temp = hArr[j];
18                 hArr[j] = hArr[j+1];
19                 hArr[j+1] = temp;
20             }
21         }
22     }
23 }
24 
25 int main(){
26     struct Hero hArr[5] = {
27         {"刘备",23,""},
28         {"关羽",22,""},
29         {"张飞",20,""},
30         {"赵云",21,""},
31         {"貂蝉",19,""}
32     };
33 
34     int len = sizeof(hArr) / sizeof(hArr[0]);
35 
36     for (int i = 0; i < len; i++){
37         cout << "name:" << hArr[i].name << "age:" << hArr[i].age <<
38         "sex:" << hArr[i].sex << endl;
39     }
40 
41     bubbleSort(hArr, len);
42     cout << endl;
43 
44     for (int i = 0; i < len; i++){
45         cout << "name:" << hArr[i].name << "age:" << hArr[i].age <<
46         "sex:" << hArr[i].sex << endl;
47     }
48 
49     system("pause");
50     return 0;
51 }
复制代码

 

posted @   Morning枫  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示