/* * File: myvector.h * ---------------- * * Created by Julie Zelenski on 2/22/08. * */ #ifndef _myvector_h #define _myvector_h #include "genlib.h" #include "disallowcopy.h" template 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 MyVector::MyVector() { arr = new ElemType[2]; numAllocated = 2; numUsed = 0; } template MyVector::~MyVector() { delete[] arr; } template int MyVector::size() { return numUsed; } template ElemType MyVector::getAt(int index) { if (index < 0 || index >= size()) Error("Out of bounds"); return arr[index]; } template void MyVector::setAt(int index, ElemType e) { if (index < 0 || index >= size()) Error("Out of bounds"); arr[index] = e; } template void MyVector::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 void MyVector::add(ElemType s) { if (numUsed == numAllocated) doubleCapacity(); arr[numUsed++] = s; } template void MyVector::doubleCapacity() { ElemType *bigger = new ElemType[numAllocated*2]; for (int i = 0; i < numUsed; i++) bigger[i] = arr[i]; delete[] arr; arr = bigger; numAllocated*= 2; }