12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- #ifndef ARRAYLIST_H
- #define ARRAYLIST_H
- #include <cstring>
- #include <iostream>
- 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--;
- }
-
- void forEach(void (*f) (T))
- {
- for(int i = 0; i < pos; i++)
- {
- f(data[i]);
- }
- }
- private:
- int capacity;
- int pos;
- T* data;
- };
- #endif
|