// A simple program to implement a *vector* like class which doubles its size // whenever it is about to overflow. // Inspired from Amortized time analysis. (although I still haven't understood // what it is all about ;) ) // Author: Rohit Krishna Kumar // Home page: http://www.geocities.com/rohitkkumar #includeusing namespace std; const int MAX=4; template class Array { T *list; int max_size; int cur_size; public: Array(void); void insert(T); T remove(void); void display(void); ~Array(); }; template Array ::Array() { max_size=MAX; list=new T[max_size]; cur_size=0; } // Inserts the element at the last position template void Array :: insert(T val) { if(cur_size == max_size) { T *temp=new T[max_size*2]; // Allocate more memory max_size<<=1; // Update the amount of memory allocated for(int i=0;i T Array :: remove(void) { // Doesn't perform any deallocation if(cur_size!=0) return list[--cur_size]; else return -1; // List empty } template void Array :: display(void) { for(int i=0;i < <<" "; cout<
Array :: ~Array() { delete[] list; } int main() { // Do a test run :) Array a; for(int i=0;i<1000000;i++) a.insert(i); for(int i=0;i<1000000;i++) cout< <<" "; }
Monday, October 31, 2005
My very own vector class
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment