[C++] 구조체 및 클래스 객체 STL map 클래스에 저장하는 방법

[C++] 구조체 및 클래스 객체 STL map 클래스에 저장하는 방법



이번 포스팅에서는 구조체의 멤버 변수들을 map 자료구조에 저장하는 방법에 대해서 알아보도록 하겠습니다.


 

지난번 포스팅에서 STL 자료구조 중 하나인 map에 대한 설명을 하고나서, 클래스나 구조체의 여러 변수들을 담고 있는 객체를 map함수를 이용해 저장을 해보고 싶어서 이렇게 구현을 해보게 되었습니다.

 


시나리오


- Student 클래스와 구조체를 선언하여 Student의 기본 멤버 변수들을 STL map에 저장하여 각각의 값들을 어떻게 출력을 하는지에 대해서 알아보도록 하겠습니다.


 

우선 아래와 같이 Visual Studio를 실행하여, C++ 빈 프로젝트를 생성해 주시기 바랍니다.





 

그리고 나서 클래스 마법사를 이용하여 Student.cpp, Student.h 파일을 생성하여 주시기 바랍니다.





이제 각각 아래와 같이 프로젝트에 알맞게 코드를 작성하여 주시기 바랍니다.



 

Student.h


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

#pragma once

#include <iostream>

#include <string>

#include <map>

 

using namespace std;

 

struct CopyStudent

{

public:

    int age; //나이

    int grade; //학년

    string name; //이름

 

public:

    void Init()

    {

        age = 15;

        grade = 3;

        name = "원숭이";

    }

};

 

class Student

{

public:

    map<int, Student*> t_map;

 

public:

    Student();

    ~Student();

 

public:

    int strAge; //나이

    int strGrade; //학년

    string strName; //이름

 

};

 

 

cs


 

Student.cpp


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include "Student.h"

 

 

//초기화

Student::Student() 

{

    this->strAge = 0;

    this->strGrade = 0;

    this->strName = "";

}

 

 

Student::~Student()

{

}

 

cs

 


 

Main.cpp


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

#include <iostream>

#include <map>

#include <string>

 

#include "Student.h"

 

using namespace std;

 

int main(void)

{

    CopyStudent copyStudent; //구조체 변수 선언

    copyStudent.Init();      //구조체 멤버변수들 초기화

 

    Student* student = new Student();      //Student 클래스 객체 선언

    student->strAge = copyStudent.age;     //구조체 멤버변수 age Student 클래스 멤버변수 strAge 저장

    student->strGrade = copyStudent.grade; //구조체 멤버변수  grade Student 클래스 멤버변수 strGrade 저장

    student->strName = copyStudent.name;   //구조체 멤버변수 Name Student 클래스 멤버변수 strName 저장

 

    cout << "학생 나이 : " << student->strAge << endl;

    cout << "학생 학년 : " << student->strGrade << endl;

    cout << "학생 이름 : " << student->strName << endl;

 

    // Student 객체를 map 저장하는 방법

    student->t_map.insert(pair<int, Student*>(1, student)); //STL map 저장

 

    map<int, Student*>::iterator iter;

 

    cout << "-------------------------map 저장되어 있는 데이터 출력------------------------- "<<endl;

    cout << endl;

    for (iter = student->t_map.begin(); iter != student->t_map.end(); ++iter)

    {

        cout << "학생 나이 : " << (*iter).second->strAge << endl;

        cout << "학생 학년 : " << (*iter).second->strGrade << endl;

        cout << "학생 이름 : " << (*iter).second->strName << endl;

    }

 

    system("pause");

 

    return 0;

}

Colored by Color Scripter

cs

 

출력 결과 화면




위와 같이 코드를 작성하고 실행을 시켜 보시게 되면 위와 같이 출력되는 것을 확인하실 수 있습니다.  코드 내용은 따로 설명 대신 주석을 달아 놓았기 때문에 충분히 이해하시고 사용하실 수 있을 것이라 생각합니다.


// Student 객체를 map 저장하는 방법

    student->t_map.insert(pair<int, Student*>(1, student)); //STL map 저장

 

    map<int, Student*>::iterator iter;

 

    cout << "-------------------------map 저장되어 있는 데이터 출력------------------------- "<<endl;

    cout << endl;

    for (iter = student->t_map.begin(); iter != student->t_map.end(); ++iter)

    {

        cout << "학생 나이 : " << (*iter).second->strAge << endl;

        cout << "학생 학년 : " << (*iter).second->strGrade << endl;

        cout << "학생 이름 : " << (*iter).second->strName << endl;

    }

 

위의 코드를 간단히 설명을 드리자면,

 

Student.h에 미리 정의 되었던 map에 Key, Value 값을 각각 int, Student* 자료형으로 선언을 하여 insert를 시켜 줍니다. 그러면 first의 값은 1이 되고, second의 값은 각각 나이, 학년, 이름이 들어있습니다.


그리고 반복자 iterator 함수를 이용하여 출력을 시켜주면 됩니다. 




감사합니다.^^



 





728x90

'C++ > C++ 문법' 카테고리의 다른 글

[C++] Call-By-Value, Call-By-Reference 예제  (0) 2018.07.13
[C++] STL map 사용 법  (0) 2018.06.20
C++ csv 파일 읽기 및 파싱 방법  (4) 2018.05.28
[C++]참조자의 이해  (0) 2018.05.10
[C++] 가변인수함수  (0) 2018.05.10

이 글을 공유하기

댓글

Designed by JB FACTORY