템플릿을 이용한 Dynamic 배열 연습
int, double, float 등 기본타입은 아무거나 다 된다.
심지어 문자열도 된다. 해놓고 보니 신기하네..
#ads_1
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T>
class TDArray{
private:
T *arr;
int size; //배열크기
int count; //실제 들어있는 갯수
public:
TDArray(int asize=10);
~TDArray();
T &Insert(int idx, T ele);
T &Append(T ele);
void Remove(int idx);
const int GetSize(){ return size; }
const int GetCount(){ return count; }
void Dump();
T &operator [](int idx);
};
template <typename T>
TDArray<T>::TDArray(int asize):size(asize),count(0){
arr = (T *)malloc(sizeof(T) * size);
}
template <typename T>
TDArray<T>::~TDArray(){
free(arr);
}
template <typename T>
T &TDArray<T>::Insert(int idx, T ele){
int num = count + 1;
if(num > size){
arr = (T *)realloc(arr, sizeof(T) * num);
size++;
}
memmove(arr+(idx+1), arr+idx, (count - idx) * sizeof(T));
arr[idx] = ele;
count++;
return arr[idx];
}
/*
template<> char* &TDArray<char *>::Insert(int idx, char* ele){
int num = count + 1;
if(num > size){
arr = (char **)realloc(arr, sizeof(char *) * num);
}
}
*/
template <typename T>
T &TDArray<T>::Append(T ele){
return Insert(count, ele);
}
template <typename T>
void TDArray<T>::Remove(int idx){
memmove(arr+idx, arr+(idx+1), (count - (idx + 1)) * sizeof(T));
count--;
}
template <typename T>
void TDArray<T>::Dump(){
for(int i=0;i<count;i++){
cout << i << " : " << arr[i] << endl;
}
}
template <typename T>
T &TDArray<T>::operator[](int idx){
return arr[idx];
}
int main(){
TDArray<char> a1;
a1.Append('A');
a1.Append('B');
a1.Append('C');
a1.Append('D');
a1.Append('E');
a1.Append('F');
a1.Remove(0);
a1.Append('G');
a1.Append('H');
a1.Append('I');
a1.Append('J');
a1.Dump();
a1.Insert(3, 'Z');
a1.Dump();
cout << "a1[3] = " << a1[3] << endl;
cout << "cout : " << a1.GetCount() << ", size : " << a1.GetSize() << endl;
cout << "-----------------------------" << endl;
TDArray<int> a2;
a2.Append(1);
a2.Append(2);
a2.Append(3);
a2.Remove(0);
a2.Append(4);
a2.Dump();
a2.Insert(3, 5);
a2.Dump();
cout << "a2[3] = " << a2[3] << endl;
cout << "cout : " << a2.GetCount() << ", size : " << a2.GetSize() << endl;
TDArray<char *> a3;
a3.Append("abc");
a3.Append("def");
a3.Append("ghi");
a3.Remove(1);
a3.Insert(1, "XYZ");
a3.Dump();
}
#ads_1