본문 바로가기
둥지/알고리즘

Array, Vector 구현

by 까닭 2023. 2. 20.
#include <iostream>
#include <array>
#include <assert.h>

using namespace std;

template<typename T, size_t S>
class Array
{
    T* Array_;
    size_t Size_;

public:
    Array()
        : Array_(nullptr)
        , Size_(S)
    {
        Array_ = new T[Size_];
    }

    ~Array()
    {
        delete[] Array_;
        Array_ = nullptr;
    }

    size_t Capacity()
    {
        return Size_;
    }

    void Resize(size_t _Size)
    {
        T* Temp = Array_;
        Array_ = new T[_Size];

        for (size_t i = 0; i < _Size; i++)
        {
            Array_[i] = Temp[i];
        }

        if (nullptr != Temp)
        {
            delete Temp;
            Temp = nullptr;
        }

        Size_ = _Size;
    }

    T& operator[](size_t _Index)
    {
        if (Size_ <= _Index)
        {
            assert(false);
        }

        return Array_[_Index];
    }
    
    void operator=(const Array& _Array)
    {
        Resize(_Array->Size_);

        for (size_t i = 0; i < Size_; i++)
        {
            Array_[i] = _Array[i];
        }
    }
    
    T& At(size_t _Index)
    {
        return Array_[_Index];
    }
};

template<typename T>
class MyVecotr
{
    Array<T, 0> Array_;
    size_t Size_;

public:
    MyVecotr()
        : Array_(0)
        , Size_(0)
    {
    }

    void Resize(size_t _Size)
    {
        Array_.Resize(_Size);
        Size_ = _Size;
    }

    void push_back(const T& _Data)
    {
        if (Size_ >= Array_.Capacity())
        {
            Array_.Resize(static_cast<size_t>((Size_ + 1) * 1.5f));
        }

        Array_[Size_] = _Data;
        ++Size_;
    }

    void Resize(size_t _SizeData)
    {
        Array_.Resize(_SizeData);
        Size_ = _SizeData;
    }

    void Reserve(size_t _SizeData)
    {
        Array_.Resize(_SizeData);
    }


};

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    std::array<int, 3> arr = {1, 2, 3};

    Array<int, 3> arr1 = {};
    arr1[0] = 1;
    arr1[1] = 2;
    arr1[2] = 3;

    for (size_t i = 0; i < arr1.Capacity(); i++)
    {
        std::cout << arr1[i] << std::endl;
    }

    return 0;
}

'둥지 > 알고리즘' 카테고리의 다른 글

퀵 정렬  (0) 2023.02.26
버블 정렬  (0) 2023.02.25
[백준 1992] 쿼드 트리  (0) 2023.02.20
리스트 구현  (0) 2023.02.17
큐 구현  (0) 2023.02.10