Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// http://www.cplusplus.com/forum/beginner/75558/
- #ifndef MYARRAY_H
- #define MYARRAY_H
- #include <iostream>
- #include <cstdlib>
- template <class T>
- class myArray
- {
- private:
- T * myArr;
- int size;
- int startpos;
- int endpos;
- public:
- myArray(int elements);
- myArray(int start, int end);
- ~myArray();
- void SetNULL();
- T & operator[](int i);
- friend std::ostream & operator<<(std::ostream & os, myArray<T> & arr)
- {
- os << "{";
- for(int i = 0; i < arr.size; i++)
- {
- if(i == (arr.size - 1))
- os << arr.myArr[i];
- else
- os << arr.myArr[i] << ",";
- }
- os << "}\n";
- return os;
- }
- };
- template <class T>
- T & myArray<T>::operator[](int i)
- {
- if(i > size) //IF OUT OF BOUNDS
- throw std::string("Element out of array bounds...nothing to be done");
- else if(startpos == 0) //IF NORMAL ARRAY
- return myArr[i];
- else //IF CUSTOM BOUNDS
- {
- return myArr[(startpos + (i - 1))];
- }
- }
- template <class T>
- myArray<T>::myArray(int elements):
- size(elements), startpos(0), endpos(elements)
- {
- myArr = new T[size]; //ALLOCATE SPACE FOR ARRAY
- SetNULL(); //ZERO OUT
- }
- template <class T>
- myArray<T>::myArray(int start, int end):
- startpos(start), //START POS
- endpos(end)
- {
- if(start > end) //END IF INVALID BOUNDS
- {
- std::cerr << "Invalid start and end position..terminating...\n";
- exit(0);
- }else
- size = end - start; //DETERMINE SIZE
- myArr = new T[size]; //ALLOCATE SPACE FOR ARRAY
- SetNULL();
- }
- template <class T>
- myArray<T>::~myArray()
- {
- delete [] myArr;
- }
- template <class T>
- void myArray<T>::SetNULL() //SET ARR TO ZERO
- {
- for(int i = 0; i < size; i++)
- {
- myArr[i] = (T)0;
- }
- }
- #endif // MYARRAY_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement