C++結構陣列和巢狀結構
結構是很多語言中非常之重要的資料組織方式,讓變數成為更有意義的資訊。
想聊解他從實際例子下手比較容易體會,而巢狀陣列就是結構裡使用其他結構名稱宣告成員變數。(◕‿‿◕。)
結構變數.成員 and 結構變數.成員[索引值]
假設寫計算學生成績的程式,資料有:姓名、國文、英文、數學與三科平均~~
班上30人,各項資料儲存在宣告陣列裡頭。
- struct Scores{
- char Name[10];
- int chi;
- int eng;
- int mat;
- float avg;
- };
- int main()
- {
- struct Scores cir;
- cout << "輸入姓名:";cin >> cir.Name;
- cout << "輸入國文:";cin >> cir.chi;
- cout << "輸入英文:";cin >> cir.eng;
- cout << "輸入數學:";cin >> cir.mat;
- cir.avg = (cir.chi+cir.eng+cir.mat)/3.0f;
- cout << cir.Name <<"的平均成績為"<<cir.avg;
- }
其實主程式裏頭的 struct Scores cir; 可以不用寫,只要在結構外寫上變數名稱就好 ! !
- struct Scores{
- char Name[10];
- int chi;
- int eng;
- int mat;
- float avg;
- }cir;
超方便的喔~~
By the way,如果你是用C寫,在scanf裡,要寫成scanf("%d",&cir.chi); ,而不是 cir.&chi 要注意! !(。・ˇ_ˇ・。)
- struct grade{
- char Name[10];
- int score[3];
- float avg;
- }cirl[3];
- int main()
- {
- for(int i=0;i<3;i++)
- {
- cout << "輸入姓名:";cin >> cirl[i].Name;
- cout << "輸入國文:";cin >> cirl[i].score[0];
- cout << "輸入英文:";cin >> cirl[i].score[1];
- cout << "輸入數學:";cin >> cirl[i].score[2];
- cirl[i].avg = (cirl[i].score[0]+cirl[i].score[1]+cirl[i].score[2])/3.0f;
- }
- for(int i=0;i<3;i++)
- cout << cirl[i].Name << "的平均成績為" << cirl[i].avg << endl;
- }
陣列運用看程式碼可能還是"母撒撒"(  ̄(エ) ̄),看圖吧~~
邊看圖在看程式碼,是阿呆也看得懂在幹嘛\(^o^)/
很多新手可能不習慣這個,都是一鼓腦兒把東西放在主程式,搞得亂78糟Σ(´д ';)
然而巢狀結構則是結構裡有結構的概念~~
那幹嘛不用一個就好啦,向陣列一樣(・A・)
舉例比較好懂,今天除了學生,在外加老師好了,
學生要打學號和年級;老師則是編號和年資~~
- struct Teacher{
- int TID;
- int Years;
- };
- struct Student{
- int SID;
- int SDe;
- };
- struct PersonalInfo{
- char Name[10];
- int Type;
- union{
- struct Teacher tea;
- struct Student stu;
- };
- }person;
- int main()
- {
- char it;
- cout << "輸入t老師、s學生:";cin >> it;
- person.Type = it;
- if(it=='t')
- {
- cout << "老師名字:"; cin >> person.Name;
- cout << "老師編號:"; cin >> person.tea.TID;
- cout << "老師年資:"; cin >> person.tea.Years;
- }
- else
- {
- cout << "學生名字:"; cin >> person.Name;
- cout << "學生學號:"; cin >> person.stu.SID;
- cout << "年級:"; cin >> person.stu.SDe;
- }
- if(person.Type=='t')
- cout << person.Name << "老師的編號:" << person.tea.TID
- << "\t服務年資:" << person.tea.Years <<endl;
- else
- cout << person.Name << "學生的學號:" << person.stu.SID
- << "\t年級:" << person.stu.SDe <<endl;
- }
於是乎,不用動腦想太多東西, 分類好就可以了
程式裡的union一定要學起來,它是用來儲存其他結構內的內容,到你想要的結構內,老師和學生的儲存空間共用地
END ლ(◉◞౪◟◉ )ლ