inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

홍정모의 따라하며 배우는 C++

10.6 컨테이너 클래스

구현해본 코드입니다! 피드백을 받고 싶어 올려봅니다 (+부족하지만 참고하실 분들 있으시면 조금이라도 도움드리고자 올려봅니다!)

299

강민혁

작성한 질문수 2

1

강의 정말 잘듣고 있습니다. 대학교에 입학한 후 코딩을 처음 배운게 파이썬이었고, 파이썬으로 스타트업에서 머신러닝 프로젝트도 하면서 여러 사람들과 협업하기도 하며 나름 객체지향에 대해서 잘 알고 있다고 생각했는데, 교수님의 강의를 듣고 C++로 객체지향을 배워보니 그동안 제가 얼마나 기초가 부족했는지 알 수 있었습니다. 교수님 강의를 듣기 전까지 1년 이상 코딩에서 재미를 찾지 못하여 손을 놨었습니다. 그런데 이 강의에서 제가 모르는지도 몰랐던 것들을 알게되니 정말 감회가 남다르고, 다시 코딩이 재밌어졌습니다!^^ 정말 감사합니다! 최근에는 클린 코드와 클린 아키텍쳐에 대해서도 같이 공부하면서 교수님이 말씀하시는 정돈되고 읽기 좋은 코드가 무엇인지 조금씩 공부하고 있습니다. 나름 클린하게 구현해보려고 노력하면서 수업 따라가고 있습니다! 현재 군대에서 교수님 강의를 듣고 있는데, 교수님덕분에 제 꿈을 다시 일으키고 기반을 제대로 닦을 수 있을 것 같습니다! 남은 강의도 성실하게 듣겠습니다! 

누구든지 피드백 해주시면 정말 감사하겠습니다! 또 혹시나 구현이 어렵거나 하신 분들을 위해 코드 공유합니다. 

#include <iostream>
#include <initializer_list>
#include <cassert>

using namespace std;

class IntArray
{
private:
    int m_length = 0;
    int *m_data = nullptr;
    const int one_digit = 1;

public:
    IntArray(const unsigned int &len_in)
        :   m_length(len_in)
    {
        initialize(m_length);
    }

    IntArray(const initializer_list<int> &list)
        : IntArray(list.size()) 
    {
        int count = 0;
        for (auto & element : list)
        {
            m_data[count] = element;
            count++;
        }
    }

    ~IntArray()
    {
        delete [] m_data;
    }

    void initialize(const unsigned int &len_in)
    {
        m_data = new int[len_in];
    }

    void reset()
    {
        delete [] m_data;
        m_data = nullptr;
        m_length = 0;
    }

    void resize(const unsigned int &len_in)
    {
        IntArray temp(len_in);
        
        copyAll(temp, *this);
        
        resetAndAssignment(temp);
    }
    
    void insertBefore(const int &value, const int &ix)
    {
        IntArray temp(m_length + one_digit);
        
        copyOriginalFromZeroToIx(temp, *this, ix - one_digit);
        temp.setValue(value, ix);
        copyOriginalFromIXToEnd(temp, *this, ix + one_digit, ix);

        resetAndAssignment(temp);
    }
    
    void remove(const int &ix)
    {
        IntArray temp(m_length - one_digit);

        copyOriginalFromZeroToIx(temp, *this, ix - one_digit);
        copyOriginalFromIXToEnd(temp, *this, ix, ix + one_digit);

        resetAndAssignment(temp);
    }

    void push_back(const int &value)
    {
        IntArray temp(m_length + one_digit);

        copyAll(temp, *this);
        int temp_end_index = temp.getLength() - one_digit;
        temp.setValue(value, temp_end_index);

        resetAndAssignment(temp);
    }

    void copyAll(IntArray & target, const IntArray & orginal)
    {
        for (int i = 0; i < target.m_length; ++i)
        {
            target.m_data[i] = orginal.m_data[i];
        }
    }

    void copyOriginalFromZeroToIx(IntArray & target, IntArray & original, const unsigned int & to_ix)
    {
        // TODO: 방어적 프로그래밍 - to_ix가 배열 길이를 벗어날 때.
        for (int i = 0; i < to_ix + one_digit; ++i)
        {
            target.m_data[i] = original.m_data[i];
        }
    }

    void copyOriginalFromIXToEnd(IntArray & target, IntArray & original, const unsigned int & from_ix_target, const unsigned int & from_ix_original)
    {
        // TODO: 방어적 프로그래밍 - to_ix가 배열 길이를 벗어날 때.
        unsigned int count = from_ix_original;
        for (int i = from_ix_target; i < target.getLength(); ++i)
        {
            target.m_data[i] = original.m_data[count];
            count++;
        }
    }

    void resetAndAssignment(IntArray & intarray)
    {
        this->reset();
        *this = intarray;
    }

    int getLength()
    {
        return m_length;
    }

    void setValue(const int &value, const int &ix)
    {
        //TODO: 방어적 프로그래밍 - 인덱스가 배열 범위를 벗어날 때
        m_data[ix] = value;
    }

    IntArray& operator = (IntArray & source)
    {
        this->m_length = source.m_length;
        this->m_data = new int[this->m_length];
        copyAll(*this, source);
    }

    friend ostream& operator << (ostream& out, IntArray & intarray)
    {
        for (int i = 0; i < intarray.getLength(); ++i)
        {
            out << intarray.m_data[i] << " ";
        }
        return out;
    }
};

int main()
{
    // constructor test - OK
    IntArray my_arr{ 1, 3, 5, 7, 9 };
    cout << "constructor test: " << endl;
    cout << my_arr << endl;
    
    // resize test - OK
    my_arr.resize(8);
    cout << "resize test: " << endl;
    cout << my_arr << endl;
    cout << "Length: " << my_arr.getLength() << endl ;
    my_arr.resize(3);
    cout << my_arr << endl;
    cout << "Length: " << my_arr.getLength() << endl;

    // copyOriginalFromZeroToIx test - OK
    IntArray arr1{1, 3, 5, 7 ,9 };
    IntArray arr2{2, 4, 6, 8, 10};
    arr1.copyOriginalFromZeroToIx(arr1,arr2,2); 
    cout << "copyOriginalFromZeroToIx test: " << endl;
    cout << arr1 << endl;

    // copyOriginalFromIXToEnd - OK
    IntArray my_arr1{100, 200, 300, 400, 500};
    my_arr1.copyOriginalFromIXToEnd(my_arr1,arr2,2,2); // 100 200 6 8 10    OK
    cout << "copyOriginalFromIXToEnd: " << endl;
    cout << my_arr1 << endl;

    //insertBefore test - OK
    IntArray my_arr3{ 1, 3, 5, 7, 9 };
    my_arr3.insertBefore(10, 1);   // 1, 10, 3, 5, 7, 9    
    cout << "insertBefore test: " << endl;
    cout << my_arr3 << endl;
    
    // remove test - OK
    my_arr3.remove(3);             // 1, 10, 3, 7, 9       
    cout << "remove test: " << endl;
    cout << my_arr3 << endl;
    
    // push_back test - OK
    my_arr3.push_back(13);         // 1, 10, 3, 7, 9, 13   
    cout << "push_back test: " << endl;
    cout << my_arr3 << endl;

    /* result:
    constructor test: 
    1 3 5 7 9 

    resize test: 
    1 3 5 7 9 0 1041 0 
    Length: 8

    1 3 5 
    Length: 3

    copyOriginalFromZeroToIx test: 
    2 4 6 7 9 

    copyOriginalFromIXToEnd: 
    100 200 6 8 10 

    insertBefore test: 
    1 10 3 5 7 9 

    remove test: 
    1 10 3 7 9 

    push_back test: 
    1 10 3 7 9 13 
    */

    return 0;
}

C++

답변 1

2

안소

우와 열심히 공부하시네요! 화이팅입니다 ㅎㅎ 

https://www.inflearn.com/questions/108158

다른 수강생분께서 짜신 코드인데 한 번 비교해보면서 스스로 피드백 해보시는 것도 도움 되실 것 같아요! 

변수가 메모리에 저장되는 것을 알려주는 강의가 어떤강의였죠

1

461

1

메모리 주소 10진수로 출력

1

650

1

클래스 템플릿 특수화에서 boolalpha로 표현된 리턴값에 대해 질문이 있습니다.

1

496

1

여러가지 리턴 타입에 관한 강의가 어떤 걸까요?

1

529

1

메모리 주소에 관한 질분

0

676

1

인터페이스 클래스에서 reportError의 매개변수에 대해 궁금한 것이 있습니다.

0

547

1

형변환 오버로딩에서 const 관련 질문이 있습니다.

0

439

1

Digit 뒤에 reference를 사용하는 이유

0

504

1

4.2 전역 변수, 정적 변수, 내부 연결, 외부 연결

0

319

1

dat파일이...

0

536

1

TODO:대입 연산자 오버로딩에 대한 소스코드입니다.

0

640

1

복사 생성자 관련 질문이 있습니다.

0

450

1

수업 중 궁금한점이 있습니다.

1

386

1

라이브러리자체가 이해가 되지 않습니다.

0

558

1

마지막 예제 질문

0

299

1

증감연산자 위치에 따른 수행 순서 질문입니다.

0

371

1

단항 연산자 오버로딩에서 return 부분에 질문이 있습니다.

1

408

1

friend함수 관련 질문이 있습니다.

0

308

1

operator+ 정의부분에서 궁금한 것이 있습니다.

0

444

1

3분 17초 질문

0

347

1

함수에 값을 대입한다는 개념이 이해가 되지 않습니다.

0

443

1

int getvalue() const에서 const는 왜 뒤에 붙는건가요?

0

440

2

const Something &st에서 const를 빼면 안되나요?

0

296

1

friend함수는 다른 클래스의 멤버함수로 쓸 수 없나요??

1

489

1