Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- using namespace std;
- template<class T>
- class MagicBox
- {
- private:
- T* box;
- int current;
- int capacity;
- public:
- MagicBox();
- MagicBox(int cap);
- MagicBox(const MagicBox & rhs);
- MagicBox& operator=(const MagicBox& rhs);
- ~MagicBox();
- T* getBox() const;
- void setCapacity(T cap);
- const int getCapacity() const;
- const int getCurr() const;
- void insert(T item);
- void pop();
- void list() const;
- };
- template<class T>
- inline MagicBox<T>::MagicBox()
- {
- capacity = 0;
- current = -1;
- box = new T[capacity];
- }
- template<class T>
- inline MagicBox<T>::MagicBox(int cap)
- {
- capacity = cap;
- current = -1;
- box = new T[capacity];
- }
- template<class T>
- inline MagicBox<T>::MagicBox(const MagicBox& rhs)
- {
- delete[] box;
- int cap = rhs.getCapacity();
- this->box = rhs.box;
- this->capacity = cap;
- this->current = rhs.getCurr();
- }
- template <class T>
- inline MagicBox<T>& MagicBox<T>::operator=(const MagicBox<T>& rhs)
- {
- if(this != &rhs)
- {
- delete[] box;
- int cap = rhs.getCapacity();
- box = new T[cap];
- box = rhs.box;
- this->capacity = cap;
- this->current = rhs.getCurr();
- }
- return *this;
- }
- template<class T>
- inline MagicBox<T>::~MagicBox()
- {
- delete[] box;
- }
- template<class T>
- inline void MagicBox<T>::insert(T item)
- {
- if (current == capacity - 1)
- {
- int oldCap = capacity;
- capacity++;
- T* newArr = new T[capacity];
- for (int i = 0; i < oldCap; i++)
- newArr[i] = box[i];
- delete[] box;
- box = newArr;
- }
- box[++current] = item;
- }
- template<class T>
- inline void MagicBox<T>::pop()
- {
- if (current > 0)
- {
- srand(time(NULL));
- int index = rand() %current + 0;
- if(index == current)
- {
- --current;
- return;
- }
- for(int i = index; i < current; ++i)
- {
- box[i] = box[i+1];
- }
- --current;
- --capacity;
- T* newArr = new T[capacity];
- for (int i = 0; i <= current; i++)
- {
- newArr[i] = box[i];
- }
- box = newArr;
- delete[] newArr;
- }
- else{
- delete[] box;
- box = new T[0];
- current = -1;
- }
- }
- template<class T>
- inline void MagicBox<T>::list() const
- {
- if(current >= 0)
- {
- for (int i = 0; i <= current; i++)
- {
- cout << box[i] << " ";
- }
- cout << "\n";
- }
- else
- return;
- }
- template<class T>
- inline const int MagicBox<T>::getCapacity() const
- {
- return capacity;
- }
- template<class T>
- inline const int MagicBox<T>::getCurr() const
- {
- return current;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement