/* * File: myvector.h * ---------------- * * Created by Julie Zelenski on 2/22/08. * */ #ifndef _myvector_h #define _myvector_h #include "genlib.h" #include "disallowcopy.h" template <typename ElemType> class MyVector { public: MyVector(); ~MyVector(); int size(); void add(ElemType s); ElemType getAt(int index); void setAt(int index, ElemType s); void insertAt(int index, ElemType e); private: ElemType *arr; int numUsed, numAllocated; void doubleCapacity(); // this prevents default memberwise copy of Vector objects DISALLOW_COPYING(MyVector); }; // #include .cpp because of template (quiirky) #include "myvector.cpp" #endif /* * File: myvector.cpp * ------------------ * * Created by Julie Zelenski on 2/22/08. * */ #include "myvector.h" template <typename ElemType> MyVector<ElemType>::MyVector() { arr = new ElemType[2]; numAllocated = 2; numUsed = 0; } template <typename ElemType> MyVector<ElemType>::~MyVector() { delete[] arr; } template <typename ElemType> int MyVector<ElemType>::size() { return numUsed; } template <typename ElemType> ElemType MyVector<ElemType>::getAt(int index) { if (index < 0 || index >= size()) Error("Out of bounds"); return arr[index]; } template <typename ElemType> void MyVector<ElemType>::setAt(int index, ElemType e) { if (index < 0 || index >= size()) Error("Out of bounds"); arr[index] = e; } template <typename ElemType> void MyVector<ElemType>::insertAt(int index, ElemType e) { if (index < 0 || index >= size()) Error("Out of bounds"); if (numUsed == numAllocated) doubleCapacity(); for (int i = size()-1; i >= index; i--) arr[i+1] = arr[i]; arr[index] = e; numUsed++; } template <typename ElemType> void MyVector<ElemType>::add(ElemType s) { if (numUsed == numAllocated) doubleCapacity(); arr[numUsed++] = s; } template <typename ElemType> void MyVector<ElemType>::doubleCapacity() { ElemType *bigger = new ElemType[numAllocated*2]; for (int i = 0; i < numUsed; i++) bigger[i] = arr[i]; delete[] arr; arr = bigger; numAllocated*= 2; }
m_r_k