โครงสร้างคือชุดของรายการประเภทข้อมูลต่างๆ มีประโยชน์มากในการสร้างโครงสร้างข้อมูลที่ซับซ้อนด้วยเร็กคอร์ดประเภทข้อมูลที่แตกต่างกัน โครงสร้างถูกกำหนดด้วยคีย์เวิร์ด struct
ตัวอย่างโครงสร้างมีดังนี้
struct employee {
int empID;
char name[50];
float salary;
}; โปรแกรมที่เก็บข้อมูลนักศึกษาไว้ในโครงสร้างมีดังนี้
ตัวอย่าง
#include <iostream>
using namespace std;
struct student {
int rollNo;
char name[50];
float marks;
char grade;
};
int main() {
struct student s = { 12 , "Harry" , 90 , 'A' };
cout<<"The student information is given as follows:"<<endl;
cout<<endl;
cout<<"Roll Number: "<<s.rollNo<<endl;
cout<<"Name: "<<s.name<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Grade: "<<s.grade<<endl;
return 0;
} ผลลัพธ์
The student information is given as follows: Roll Number: 12 Name: Harry Marks: 90 Grade: A
ในโปรแกรมข้างต้น โครงสร้างถูกกำหนดก่อนฟังก์ชัน main() โครงสร้างประกอบด้วยหมายเลขม้วน ชื่อ เครื่องหมายและเกรดของนักเรียน ซึ่งแสดงให้เห็นในข้อมูลโค้ดต่อไปนี้
struct student {
int rollNo;
char name[50];
float marks;
char grade;
}; ในฟังก์ชัน main() วัตถุของประเภท struct student ถูกกำหนดไว้ ประกอบด้วยเลขม้วน ชื่อ เครื่องหมาย และค่าเกรด ดังแสดงไว้ดังนี้
struct student s = { 12 , "Harry" , 90 , 'A' }; ค่าโครงสร้างจะแสดงในลักษณะดังต่อไปนี้
cout<<"The student information is given as follows:"<<endl; cout<<endl; cout<<"Roll Number: "<<s.rollNo<<endl; cout<<"Name: "<<s.name<<endl; cout<<"Marks: "<<s.marks<<endl; cout<<"Grade: "<<s.grade<<endl;