Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef MY_LIST
- #define MY_LIST
- #include "Intefaces.hpp"
- template<class T>
- class List : public IList<T>
- {
- private:
- T *data;
- int len;
- int last;
- void getMoreMemory()
- {
- T *newData = new T[len * 2];
- for (int i = 0; i < len; i++)
- newData[i] = data[i];
- len *= 2;
- delete data;
- data = newData;
- }
- template<class T>
- class ListIterator : public IEnumerator<T>
- {
- private:
- T *data;
- int last;
- int current;
- public:
- ListIterator(T *data, int last)
- {
- this->data = data;
- this->last = last;
- current = -1;
- }
- virtual bool MoveNext()
- {
- if(current == last)
- return false;
- current++;
- return true;
- }
- virtual void Reset()
- {
- current = -1;
- }
- virtual T Current()
- {
- if(current == -1)
- throw "MoveNext must be called.";
- return data[current];
- }
- virtual ~ListIterator() {}
- };
- public:
- List()
- {
- data = new T[4];
- last = -1;
- len = 4;
- }
- List(IEnumerable<T> *e)
- {
- data = new T[4];
- len = 4;
- last = -1;
- IEnumerator<T> *enumerator = e->GetEnumerator();
- while (enumerator->MoveNext())
- {
- Add(enumerator->Current());
- }
- delete enumerator;
- }
- List(int lenght)
- {
- data = new T[lenght];
- len = lenght;
- last = -1;
- }
- List(const List<T> &obj)
- {
- IEnumerator<T> *e = obj.GetEnumerator();
- while (e->MoveNext())
- {
- Add(e->Current());
- }
- delete e;
- len = obj.len;
- last = obj.last;
- }
- virtual IEnumerator<T> *GetEnumerator()
- {
- return new ListIterator<T>(data, last);
- }
- virtual void Add(T item)
- {
- if (last + 1 == len)
- getMoreMemory();
- data[++last] = item;
- }
- virtual bool Remove(T item)
- {
- for (int i = 0; i < last + 1; i++)
- {
- if (data[i] == item)
- {
- for(int j = i; j < last + 1; j++)
- {
- data[j] = data[j + 1];
- }
- last--;
- return true;
- }
- }
- return false;
- }
- virtual void Insert(int index, T item)
- {
- if (index < 0 || index > last + 1)
- throw "index";
- if (last + 1 >= len)
- {
- getMoreMemory();
- }
- for (int i = last + 1; i > index; i--)
- {
- data[i] = data[i - 1];
- }
- data[index] = item;
- last++;
- }
- virtual void RemoveAt(int index)
- {
- if(index < 0 || index > last)
- throw "index";
- for(int i = index; i < last + 1; i++)
- {
- data[i] = data[i + 1];
- }
- last--;
- }
- virtual bool IsReadOnly()
- {
- return false;
- }
- virtual T &operator[](int index)
- {
- if(index < 0 || index > last + 1)
- throw "index";
- return data[index];
- }
- virtual void Clear()
- {
- last = -1;
- }
- };
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement