1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- #ifndef UNSORTEDARRAYLIST_H
- #define UNSORTEDARRAYLIST_H
- #include <cstring>
- #include <iostream>
- template<class E>
- class UnsortedArrayList
- {
- public:
- UnsortedArrayList()
- {
- data = new E[capacity];
- }
-
- virtual ~UnsortedArrayList()
- {
- delete[] data;
- }
-
- int getSize() const
- {
- return size;
- }
-
- void add(E e)
- {
- if(capacity <= size)
- {
- capacity *= 2;
- E* newData = new E[capacity];
- memcpy(newData, data, sizeof(E) * size);
- delete[] data;
- data = newData;
- }
- data[size] = e;
- size++;
- }
-
- void remove(E e)
- {
- int i = 0;
- while(i < size)
- {
- if(e == data[i])
- {
- if(i == size - 1)
- {
- memset(data + i, 0, sizeof(E));
- }
- else
- {
- data[i] = data[size - 1];
- memset(data + size - 1, 0, sizeof(E));
- }
- size--;
- }
- else
- {
- i++;
- }
- }
- }
-
- void removeIndex(int index)
- {
- if(index >= 0 && index < size)
- {
- if(size == 1 || index == size - 1)
- {
- memset(data + index, 0, sizeof(E));
- }
- else
- {
- data[index] = data[size - 1];
- memset(data + size - 1, 0, sizeof(E));
- }
- size--;
- }
- }
-
- E get(int index, E error) const
- {
- if(index >= 0 && index < size)
- {
- return data[index];
- }
- return error;
- }
-
- private:
- int size = 0;
- int capacity = 1;
- E* data;
- };
- #endif
|