123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- #ifndef ARRAYLIST_H
- #define ARRAYLIST_H
- #include <cstring>
- #include <iostream>
- #include "../Exception.h"
- template<class T>
- class ArrayList
- {
- public:
- ArrayList()
- {
- pos = 0;
- capacity = 4;
- data = new T[capacity];
- }
-
- ArrayList(const ArrayList& orig)
- {
- pos = orig.pos;
- capacity = orig.capacity;
- data = new T[capacity];
- memcpy(data, orig.data, capacity * sizeof(T));
- }
-
- ArrayList& operator=(const ArrayList& orig)
- {
- delete[] data;
-
- pos = orig.pos;
- capacity = orig.capacity;
- data = new T[capacity];
- memcpy(data, orig.data, capacity * sizeof(T));
-
- return *this;
- }
-
- virtual ~ArrayList()
- {
- delete[] data;
- }
-
- int getSize()
- {
- return pos;
- }
-
- void clear()
- {
- memset(data, 0, sizeof(T) * pos);
- pos = 0;
- }
-
- void add(T t)
- {
- if(pos >= capacity)
- {
- int newCapacity = capacity * 2;
- T* t = new T[newCapacity];
- memcpy(t, data, capacity * sizeof(T));
- delete[] data;
- data = t;
- capacity = newCapacity;
- }
- data[pos] = t;
- pos++;
- }
-
- void remove(int index)
- {
- if(index < 0 || index >= pos)
- {
- return;
- }
- for(int i = index; i < pos - 1; i++)
- {
- data[i] = data[i + 1];
- }
- memset(data + pos - 1, 0, sizeof(T));
- pos--;
- }
-
- T get(int index)
- {
- if(index < 0 || index >= pos)
- {
- throw Exception("out of bounds");
- }
- return data[index];
- }
-
- void forEach(void (*f) (T))
- {
- for(int i = 0; i < pos; i++)
- {
- f(data[i]);
- }
- }
- private:
- int capacity;
- int pos;
- T* data;
- };
- #endif
|