#include <algorithm>
#include <iostream>
using namespace std;
template <typename T>
class SimpleVector
{
private:
T* Data;
int CurrentSize;
int CurrentCapacity;
public:
// 기본 생성자
SimpleVector() : CurrentSize(0), CurrentCapacity(10)
{
Data = new T[10]();
}
// 매개변수를 받는 생성자
SimpleVector(int Capacity) : CurrentSize(0), CurrentCapacity(Capacity)
{
Data = new T[CurrentCapacity]();
}
// 복사 생성자
SimpleVector(const SimpleVector& Other) : CurrentSize(Other.CurrentSize), CurrentCapacity(Other.CurrentCapacity)
{
Data = new T[CurrentCapacity];
for (int i = 0; i < CurrentSize; ++i)
{
Data[i] = Other.Data[i];
}
}
// 소멸자
~SimpleVector()
{
delete[] Data;
}
// 데이터 삽입
void push_back(const T& Value)
{
// 현재 배열의 크기가 용량과 같다면
if (CurrentSize == CurrentCapacity)
{
CurrentCapacity += 5;
T* Temp = new T[CurrentCapacity]; // 현재 용량에 +5의 용량을 가진 동적 배열 생성
for (int i = 0; i < CurrentSize; ++i) // 기존 데이터 복사
{
Temp[i] = Data[i];
}
delete[] Data; // 기존 동적 배열 삭제
Data = Temp; // 용량 증가 시킨 동적 배열 주소 저장
}
Data[CurrentSize] = Value;
CurrentSize++;
}
// 마지막 요소 삭제
void pop_back()
{
if (CurrentSize > 0)
{
--CurrentSize;
}
}
// 현재 배열 크기 반환
int size() { return CurrentSize; }
// 현재 배열 용량 반환
int capacity() { return CurrentCapacity; }
// 배열 용량 재설정
void resize(int ResizeCapacity)
{
if (ResizeCapacity < CurrentCapacity) return;
CurrentCapacity = ResizeCapacity;
T* Temp = new T[CurrentCapacity];
for (int i = 0; i < CurrentSize; ++i)
{
Temp[i] = Data[i];
}
delete[] Data;
Data = Temp;
}
// 전체 데이터 출력
void PrintData()
{
for (int i = 0; i < CurrentSize; ++i)
{
cout << Data[i] << " ";
}
}
// 데이터 정렬
void sortData(bool ascending = true)
{
if (ascending)
{
sort(Data, Data + CurrentSize);
}
else
{
sort(Data, Data + CurrentSize, greater<T>());
}
}
};
직접 std::vector를 class로 약식 구현해보면서 stack에 배열의 size나 capacity 등 메타 데이터들이 저장되고, heap에 동적배열로 실질적인 데이터가 저장되있는 것을 확인할 수 있어서 와닿게 느껴졌다.
또한 capacity를 초과하는 입력 데이터가 들어온다면 새로운 동적배열에 기존의 데이터를 복사하는 과정이 일어난다는 것을 새로이 알게 되었다.
'내배캠 > C++' 카테고리의 다른 글
유클리드 거리 공식 (0) | 2025.01.06 |
---|---|
priority_queue (1) | 2025.01.06 |
std::regex_replace (0) | 2024.12.31 |
디자인 패턴(Observer Pattern) (1) | 2024.12.30 |
디자인 패턴(Decorator Pattern) (0) | 2024.12.30 |