구조는 다양한 데이터 유형의 항목 모음입니다. 다른 데이터 유형 레코드를 사용하여 복잡한 데이터 구조를 생성하는 데 매우 유용합니다. 구조체는 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() 함수보다 먼저 정의됩니다. 구조에는 직원 ID, 이름, 급여 및 부서가 포함됩니다. 이는 다음 코드 스니펫에 나와 있습니다.
struct employee {
int empID;
char name[50];
int salary;
char department[50];
}; main() 함수에서 struct employee 유형의 객체 배열이 정의됩니다. 여기에는 직원 ID, 이름, 급여 및 부서 값이 포함됩니다. 이것은 다음과 같이 표시됩니다.
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } }; 구조 값은 for 루프를 사용하여 표시됩니다. 이것은 다음과 같은 방식으로 표시됩니다.
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;
}