๊ณต๋ถ€/์ฝ”๋”ฉ

[C++] ๋ฒกํ„ฐ๋ฅผ ์ง์ ‘ ์ •์˜ํ•ด๋ณด์ž!

sourceoftax 2025. 8. 20. 21:29

๋™์  ๋ฐฐ์—ด๊ณผ ํ…œํ”Œ๋ฆฟ์„ ์ด์šฉํ•ด ๋ฒกํ„ฐ๋ฅผ ์ง์ ‘ ์ •์˜ํ•ด๋ณด๋Š” ๊ณผ์ •

์ด๋Ÿฐ ๋…ธ๊ฐ€๋‹ค ์—†์ด๋„ ๋ฌธ์žฅ ํ•œ ์ค„์— ๋ชจ๋“  ๊ฑธ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•ด์ฃผ์‹œ๋Š” #include <vector>์—๊ฒŒ ๊ฐ์‚ฌํ•œ ๋งˆ์Œ์„ ๊ฐ–๊ฒŒ ๋˜๋Š” ์‹œ๊ฐ„์ด๋‹ค

#ifndef MYVECTOR_H
#define MYVECTOR_H

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

template <typename T>

class MyVector
{
private:
    T* data;
    size_t size;
    size_t capacity;

    void expand()
    {
        size_t newCapacity;
        newCapacity = capacity * 2;
        T* newData = new T[newCapacity];
        for (size_t i = 0; i < size; i++) {
            newData[i] = data[i];
       }
        delete[] data;
        data = newData;
        capacity = newCapacity;
    }

public:
    MyVector(): data(nullptr), size(0), capacity(0)
    {
    }

    MyVector(const MyVector& other)
    {   
        data = new T[capacity];
        for (size_t i = 0; i < size; i++) {
            data[i] = other.data[i];
        }
    }


    MyVector& operator=(const MyVector& other)
    {
        if (this != &other) {
            delete[] data;

            capacity = other.capacity;
            size = other.size;

            data = new T[capacity];
            for (size_t i = 0; i < size; i++) {
                data[i] = other.data[i];
            }
           
    }
        return *this;
    }

    ~MyVector()
    {
        delete[] data;
    }

    void push_back(const T& value)
    {
        if (capacity >= size) {
            expand();
        }
        data[size++] = value;

    }

    void pop_back()
    {
        if (size != 0) {
            size--;
        }
    }

    T& operator[](size_t index)
    {
        return data[index];
    }

    const T& operator[](size_t index) const
    {
        return data[index];
    }

    T& at(size_t index)
    {
        if (index > size) {
            throw out_of_range();
        }
        return data[index];
    }

    size_t get_size() const
    {
        return size;
    }

    size_t get_capacity() const
    {
        return capacity;
    }

    bool empty() const
    {
        return size == 0;
    }

    void print() const
    {
        cout << "[";
        for (size_t i = 0; i < size; i++) {
            cout << data[i];
            if (i < size - 1) cout << ", ";
        }
        cout << "]" << endl;
    }
};

#endif