코딩/C++

[C++] Struct, Union 이해하기

peter_00 2025. 1. 21. 12:41
반응형

Struct 를 간단하게 말하자면 관련된 데이터를 묶는것이다

클래스와 유사하지만 기본적으로 모든 멤버가 public

예시)

#include <iostream>
using namespace std;

struct Student {
    int id;
    string name;
};

int main() {
    Student s = {101, "Alice"};
    cout << s.id << " " << s.name << endl;  // 결과값: 101 Alice
    return 0;
}

int id 와 string name 을 stuct Student 에 보관하여

main 에서 불러온다

s.id 를 이용해서 Student s 로 지정했던 101 을 불러오고

s.name 을 이용해서 Alice 를 불러온다

 

Nested Structs

Struct 는 또 다른 struct 를 포함 할 수 있다. 

이걸 이용해서 struct 안에 struct 를 보관 할 수 있다.

#include <iostream>
using namespace std;

struct Address {
    string city;
    int zip;
};

struct Student {
    int id;
    string name;
    Address addr;
};

int main() {
    Student s = {101, "Alice", {"Seoul", 12345}};
    cout << s.name << " lives in " << s.addr.city << ", " << s.addr.zip << endl;
    // 결과값: Alice lives in Seoul, 12345
    return 0;
}

struct Student 에 있는 Address addr 은 struct Address 의 정보를 포함하고 있다.

그렇기때문에 Student s 만을 이용해서 s.addr.city 그리고 s.addr.zip 즉 Address 정보를 불러올 수 있다

 

Struct 는 멤버 함수를 가질 수 있지만 클래스 사용이 더 적합하다 (void 사용)

#include <iostream>
using namespace std;

struct Test {
    int number;
    void setNumber(int n) { number = n; }
    void show() { cout << "Number: " << number << endl; }
};

int main() {
    Test t;
    t.setNumber(42);
    t.show();  // 결과값: Number: 42
    return 0;
}

void 를 사용해서 function 을 지정했다

 

Union

Union 은 Struct 와 비슷하지만 모든 멤버가 같은 메모리를 공유한다.

#include <iostream>
using namespace std;

union Data {
    int i;
    float f;
};

int main() {
    Data d;
    d.i = 10;
    cout << d.i << endl;  // 결과값: 10
    d.f = 3.14;
    cout << d.f << endl;  // 결과값: 3.14
    return 0;
}

 

Random

c++11 은 random 라이브러리를 제공한다.

#include <random>
#include <iostream>
using namespace std;

int main() {
    default_random_engine eng;
    uniform_int_distribution<int> dist(1, 6);
    for (int i = 0; i < 5; ++i)
        cout << dist(eng) << " ";  // 결과값: 1에서 6 사이의 랜덤값
    return 0;
}

 

Atoi 와 stringstream 의 차이

atoi 는 문자열을 정수로 변환하는 데 사용된다.

stringstream 도 위와 같이 사용된다

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    string str = "123";
    int num;
    stringstream(str) >> num;
    cout << num + 1 << endl;  // 결과값: 124
    return 0;
}

string 인 str 이 123 으로 지정되어 있지만 

stringstream 을 이용해서 정수로 변환 후 +1 을 해서 결과값이 124이다

 

atoi 와 stringstream 은 차이점이 있다

 

atoi 는 문자열을 정수(int)로만 변환이 가능하다

float 또는 double 으로는 변환이 불가하다

그리고 atoi 를 사용하기 위해서는 반드시 문자열 (const char*) 이 필요로 하다

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
    const char* str = "123";
    int num = atoi(str);
    cout << num + 1 << endl;  // 출력: 124
    return 0;
}

 

stringstream 은 다양한 타입으로 변환할 수 있다

int float double 등

#include <sstream>
#include <iostream>
using namespace std;

int main() {
    string str = "123.45";
    double num;
    stringstream(str) >> num;
    cout << num + 1 << endl;  // 출력: 124.45
    return 0;
}

 

에러처리 기능에서도 차이점이 있다

atoi 는  에러가 생기면 0 혹은 결과를 나타내지 않는다

const char* invalidStr = "abc123";
int result = atoi(invalidStr);  // 결과: 정의되지 않거나 result = 0

 

stringstream 은 성공 여부를 확인할 수 있다 

fail() 을 이용해서 변환 성공 여부를 판단 가능하다.

#include <sstream>
#include <iostream>
using namespace std;

int main() {
    string str = "abc123";
    int num;
    stringstream ss(str);
    if (ss >> num) {
        cout << "변환 성공: " << num << endl;
    } else {
        cout << "변환 실패!" << endl;  // 출력: 변환 실패!
    }
    return 0;
}

if else 를 활용해서 성공인지 실패인지 결과로 나타낼 수 있다

반응형