结构体例题

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 @ 2022-10-31 19:02  Morning枫  阅读(34)  评论(0编辑  收藏  举报