Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #ifndef MYVECTOR_H_INCLUDED
- #define MYVECTOR_H_INCLUDED
- template <class T>
- class MyVector
- {
- int vsize;
- int maxsize;
- T *array;
- void alloc_new();
- void dealloc();
- public:
- MyVector();
- MyVector(int );
- ~MyVector();
- void push_back(T);
- void pop_back();
- int size();
- T operator[](int);
- T& at(int i);
- };
- template<class T>
- MyVector<T> :: MyVector()
- {
- maxsize=5;
- array=new T[maxsize];
- vsize=0;
- }
- template<class T>
- MyVector<T> :: MyVector(int i)
- {
- maxsize=i;
- array=new T[maxsize];
- vsize=0;
- }
- template<class T>
- MyVector<T> :: ~MyVector()
- {
- delete[] array;
- }
- template<class T>
- void MyVector<T> :: push_back(T i)
- {
- if(vsize+1>maxsize)
- alloc_new();
- array[vsize]=i;
- vsize++;
- }
- template<class T>
- T MyVector<T> :: operator[](int i)
- {
- return array[i];
- }
- template<class T>
- T& MyVector<T> :: at(int i)
- {
- if(i<vsize)
- return array[i];
- std::cout<<"Error: Out of range";exit(1);
- }
- template<class T>
- void MyVector<T> :: pop_back()
- {
- if(vsize>0)
- {
- vsize--;
- dealloc();
- }
- }
- template<class T>
- void MyVector<T> :: dealloc()
- {
- T* temp;
- temp=new T[vsize];
- for(int i=0;i<vsize;i++)
- temp[i]=array[i];
- delete []array;
- array=temp;
- }
- template<class T>
- void MyVector<T> :: alloc_new()
- {
- maxsize=vsize*2;
- T *tmp=new T[maxsize];
- for(int i=0;i<vsize;i++)
- tmp[i]=array[i];
- delete[]array;
- array=tmp;
- }
- template<class T>
- int MyVector<T> :: size()
- {
- return vsize;
- }
- #endif // MYVECTOR_H_INCLUDED
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement