๋์ ๋ฐฐ์ด๊ณผ ํ ํ๋ฆฟ์ ์ด์ฉํด ๋ฒกํฐ๋ฅผ ์ง์ ์ ์ํด๋ณด๋ ๊ณผ์
์ด๋ฐ ๋ ธ๊ฐ๋ค ์์ด๋ ๋ฌธ์ฅ ํ ์ค์ ๋ชจ๋ ๊ฑธ ๊ฐ๋ฅํ๊ฒ ํด์ฃผ์๋ #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'๊ณต๋ถ > ์ฝ๋ฉ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ์๊ณ ๋ฆฌ์ฆ ์คํฐ๋ 2์ฃผ์ฐจ ๊ฒฐ์ฐ (0) | 2025.10.05 |
|---|---|
| [์๊ณ ๋ฆฌ์ฆ ์คํฐ๋] 1์ฃผ์ฐจ ๊ฒฐ์ฐ (0) | 2025.09.27 |
| ์๊ฐ/๊ณต๊ฐ ๋ณต์ก๋์ Big-O ํ๊ธฐ๋ฒ (1) | 2025.08.18 |
| [C++] vector์ pair ์ฐ์ต (2) | 2025.08.17 |
| [C++] ๊ทธ์น๋ง ์ด๋ ๊ฒ๋ผ๋ ํ์ง ์์ผ๋ฉด iostream์ด ์๋ ๋์๊ฒ ๊ด์ฌ๋ ์ฃผ์ง ์๋๊ฑธ(๋ถ๋ฆฌ ์ปดํ์ผ) (4) | 2025.08.11 |