โครงสร้างคือชุดของรายการประเภทข้อมูลต่างๆ มีประโยชน์มากในการสร้างโครงสร้างข้อมูลที่ซับซ้อนด้วยเร็กคอร์ดประเภทข้อมูลที่แตกต่างกัน โครงสร้างถูกกำหนดด้วยคีย์เวิร์ด struct
ตัวอย่างของโครงสร้างมีดังนี้ −
struct employee {
int empID;
char name[50];
float salary;
}; มีโปรแกรมจัดเก็บและแสดงข้อมูลโดยใช้โครงสร้างดังนี้
ตัวอย่าง
#include <iostream>
using namespace std;
struct employee {
int empID;
char name[50];
int salary;
char department[50];
};
int main() {
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };
cout<<"The employee information is given as follows:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
cout<<"Employee ID: "<<emp[i].empID<<endl;
cout<<"Name: "<<emp[i].name<<endl;
cout<<"Salary: "<<emp[i].salary<<endl;
cout<<"Department: "<<emp[i].department<<endl;
cout<<endl;
}
return 0;
} ผลลัพธ์
The employee information is given as follows: Employee ID: 1 Name: Harry Salary: 20000 Department: Finance Employee ID: 2 Name: Sally Salary: 50000 Department: HR Employee ID: 3 Name: John Salary: 15000 Department: Technical
ในโปรแกรมข้างต้น โครงสร้างถูกกำหนดก่อนฟังก์ชัน main() โครงสร้างประกอบด้วยรหัสพนักงาน ชื่อ เงินเดือน และแผนกของพนักงาน ซึ่งแสดงให้เห็นในข้อมูลโค้ดต่อไปนี้
struct employee {
int empID;
char name[50];
int salary;
char department[50];
}; ในฟังก์ชัน main() อาร์เรย์อ็อบเจ็กต์ของประเภท struct พนักงานถูกกำหนดไว้ ซึ่งประกอบด้วยรหัสพนักงาน ชื่อ เงินเดือน และค่าแผนก ดังแสดงไว้ดังนี้
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } }; ค่าโครงสร้างจะแสดงโดยใช้การวนซ้ำ ซึ่งจะแสดงในลักษณะดังต่อไปนี้
cout<<"The employee information is given as follows:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
cout<<"Employee ID: "<<emp[i].empID<<endl;
cout<<"Name: "<<emp[i].name<<endl;
cout<<"Salary: "<<emp[i].salary<<endl;
cout<<"Department: "<<emp[i].department<<endl;
cout<<endl;
}