코딩 58일차 C/C++

마스터피스·2024년 1월 10일
0

C/ C++ 

목록 보기
30/35
post-thumbnail
  1. STL
  • STL이란 무엇일까요? Standard Template Library가 STL 입니다. 이 STL을 활용하면 여러 가지 타입에 대응하는 유용한 클래스를 만들어내어 소스코드의 재사용성을 굉장히 높여주게 됩니다.
    이 활용예시를 소스코드를 통해 알아보게 됩니다.
- template <typename T>

: STL 클래스에서 타입을 나중에 지정하겠다고 명시하는 방법. 여기에서 T가 나중에 지정할 타입 이름이 된다.

예제코드)

#include <cstdio>
#include <string>

template <typename T>
class Myclass {
public:
    T value;

};

template <typename T>
void swap(T* a, T* b) {
    T tmp;
    tmp = *a;
    *a = *b; 
    *b = tmp;

}

int main() {
    Myclass<int>* m = new Myclass<int>();
    m->value = 100; // 여기서는 int
    Myclass<std::string>* ms = new Myclass<std::string>();
    ms->value = "Hello World"; // 여기서는 str

    std::string value1 = "Hello";
    std::string value2 = "World";

    swap<std::string>(&value1, &value2);

    printf("value1 : %s\n", value1.c_str());
    printf("value2 : %s\n", value2.c_str());

    return 0;
}
  1. STL을 활용해서 가변 배열 클래스 라이브러리 만들기
  • STL을 활용해서 가변 배열 클래스 라이브러리를 만들어 봅니다. 이렇게 만들어진 가변 배열 클래스는 여러 가지 타입에 대응될 수 있기 때문에 코드의 재사용성이 좋습니다. 이런 형태가 아닌 일반적인 형태로 가변 배열 클래스를 만들게 되면 여러 가지 타입에 대응되는 모든 가변 배열 클래스를 그때그때 만들어둬야 합니다. 이는 코드의 재사용성에 굉장히 안 좋은 영향을 끼치게 됩니다.
    이를 해결해주는 것이 STL입니다.

예제코드)

#include <cstdio>
#include <string>

template <typename T>
class Myarray {
public:
    T* arrayItem; // 배열포인터
    int count = 0;
    int capacity = 8;

    Myarray() {
        arrayItem = new T[capacity];
    }

    virtual ~Myarray() { // 소멸자는 virtual을 붙여줘야한다. 잊지말기.
        delete[] arrayItem;
    }


    void putValue(T value) {
        if (capacity <= count) {
            printf("배열의 캐파시티가 두배로 늘어났습니다\n");
            T* newarray = new T[capacity * 2];
            capacity = capacity * 2;
            for (int i = 0; i < count; i++) {
                newarray[i] = arrayItem[i];
            }
            delete[] arrayItem;
            arrayItem = newarray;

        }		
        arrayItem[count] = value;
        count++;
    }
};



int main() {
    Myarray<int> m = Myarray<int>();

    m.putValue(100);
    m.putValue(200);
    m.putValue(300);
    m.putValue(400);
    m.putValue(500);
    m.putValue(600);
    m.putValue(700);
    m.putValue(800);
    m.putValue(900);

    for (int i = 0; i < m.count; i++) {
        printf("%d\n", m.arrayItem[i]);
    }



    return 0;
}
  1. STL 선언과 정의 분리
  • STL은 선언과 정의를 분리할 수 없습니다. STL 은 컴파일 타임에 마치 매크로와 같은 전처리를 통해 그때그때 알맞은 클래스나 함수로 번역되기 때문입니다.

*더 알아보기

이 STL 때문에 C++의 컴파일은 또 극악으로 느린 빌드/컴파일 타임을 갖게 됩니다. 하지만 빌드/컴파일 타임을 희생한 만큼 만들어진 프로그램의 퍼포먼스는 비슷한 코딩 방법을 채택하고 있는 그 어떤 언어들보다도 빠른 속도를 갖습니다.

++ 꿀팁 crtl + . 눌러서 누락된 내용 한번에 추가가능

과제형 문제)

sol)

#include <cstdio>
#include <string>

template <typename T>
class Myarray {
private:
    T* arrayItem; // 배열포인터
    int count = 0;
    int capacity = 8;

public:
    Myarray() {
        arrayItem = new T[capacity];
    }

    virtual ~Myarray() { // 소멸자는 virtual을 붙여줘야한다. 잊지말기.
        delete[] arrayItem;
    }


    void putValue(T value) {
        if (capacity <= count) {
            printf("배열의 캐파시티가 두배로 늘어났습니다\n");
            T* newarray = new T[capacity * 2];
            capacity = capacity * 2;
            for (int i = 0; i < count; i++) {
                newarray[i] = arrayItem[i];
            }
            delete[] arrayItem;
            arrayItem = newarray;

        }		
        arrayItem[count] = value;
        count++;
    }

    int getCount() {
        return count;
    }

    T getValue(int index) {
        return arrayItem[index];
    }

    // value 값이 존재하는지 확인하는 함수 
    bool contains(T value) {
        for (int i = 0; i < count; i++) {
            if (value == arrayItem[i]) {
                return true;
            }
        }
        return false;


    }

    // 값을 변경
    void replace(int index, T value) {
        if (index < count) {
            arrayItem[index] = value;
        }

    }

    // 값을 삭제 (빈 공간을 채워줘야 한다.)
    void erase(int index) {
        for (int i = index; i < count - 1; i++) {
            arrayItem[i] = arrayItem[i + 1];
        }
        count--;
    }
};




int main() {
    Myarray<int> m = Myarray<int>();

    m.putValue(10);
    m.putValue(11);
    m.putValue(15);
    m.putValue(20);

    m.replace(2, 100);

    if (m.contains(44)) {
        printf("값을 포함하고 있습니다.");
    }
    else {
        printf("포함 하고 있지 않습니다.");
    }


    return 0;
}
profile
코딩 일지

0개의 댓글