//확장배열을 만들어보자아~~
#include <iostream>
using namespace std;
using std::cout;
using std::endl;
template <class T>
class MyVector
{
T *base;
int capacity;
int usage;
public:
MyVector(int _capacity=0, T in=0);
virtual ~MyVector();
void PushBack(T in);
void Insert(int index, T in);
void Erase(int index);
T &operator[](int index);
int Usage();
int Capacity();
void InitProperty();
void ExtendStorage(int _capacity);
void PushBacks(int cnt, T in);
void ShiftRight(int index);
void ShiftLeft(int index);
bool AvailIndex(int index);
};
template <class T>
MyVector<T>::MyVector(int _capacity, T in) //생성
{
InitProperty();
capacity = _capacity; //capacity 초기화
base = new T[capacity];
for(int i=0; i<capacity; i++)
{
PushBack(in);
}
}
template <class T>
MyVector<T>::~MyVector() //소멸
{
delete [] base;
}
template <class T>
void MyVector<T>::PushBack(T in)
{
if(capacity==usage)
{
if(capacity)
{
ExtendStorage(capacity*2);
}
else
{
ExtendStorage(1);
}
}
base[usage] = in;
usage++;
}
template <class T>
void MyVector<T>::Insert(int index, T in)
{
if(capacity == usage)
{
if(capacity)
{
ExtendStorage(capacity*2);
}
else
{
ExtendStorage(1);
}
ShiftRight(index);
base[index] = in;
usage++;
}
}
template <class T>
void MyVector<T>::Erase(int index)
{
ShiftLeft(index);
usage--;
}
template <class T>
T& MyVector<T>::operator[](int index)
{
if(!AvailIndex(index))
{
throw "유효하지 않은 인덱스임";
}
return base[index];
}
template <class T>
int MyVector<T>::Usage()
{
return usage;
}
template <class T>
int MyVector<T>::Capacity()
{
return capacity;
}
template <class T>
void MyVector<T>::InitProperty()
{
capacity =0;
usage =0;
}
template <class T>
void MyVector<T>::ExtendStorage(int _capacity)
{
T *temp = base;
base = new T [_capacity];
for(int i=0; i<_capacity; i++)
{
base[i] = temp[i];
}
delete [] temp;
}
template <class T>
void MyVector<T>::PushBacks(int cnt, T in)
{
for(int i=0; i<cnt; i++)
{
PushBack(in);
}
}
template <class T>
void MyVector<T>::ShiftRight(int index)
{
for(int i=usage-1; i>= index; i--)
{
base[i+1] = base[i];
}
}
template <class T>
void MyVector<T>::ShiftLeft(int index)
{
for(int i=index; i<=usage-1; i++)
{
base[i] = base[i+1];
}
}
template <class T>
bool MyVector<T>::AvailIndex(int index)
{
return index<usage;
}
'programming > C++' 카테고리의 다른 글
보간법 (0) | 2010.06.10 |
---|---|
객체출력자 (0) | 2009.11.24 |
1. 순차보관 (0) | 2009.11.19 |
3. Hash Function에 의해 자료를 보관 (0) | 2009.11.19 |
2. 특정 키순으로 보관(complete) (0) | 2009.11.19 |