ArrayList.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #ifndef ARRAYLIST_H
  2. #define ARRAYLIST_H
  3. #include <cstring>
  4. template<class T>
  5. class ArrayList
  6. {
  7. public:
  8. ArrayList()
  9. {
  10. pos = 0;
  11. capacity = 4;
  12. data = new T[capacity];
  13. }
  14. ArrayList(const ArrayList& orig)
  15. {
  16. pos = orig.pos;
  17. capacity = orig.capacity;
  18. data = new T[capacity];
  19. memcpy(data, orig.data, capacity * sizeof(T));
  20. }
  21. ArrayList& operator=(const ArrayList& orig)
  22. {
  23. delete[] data;
  24. pos = orig.pos;
  25. capacity = orig.capacity;
  26. data = new T[capacity];
  27. memcpy(data, orig.data, capacity * sizeof(T));
  28. return *this;
  29. }
  30. virtual ~ArrayList()
  31. {
  32. delete[] data;
  33. }
  34. int getSize()
  35. {
  36. return pos;
  37. }
  38. void clear()
  39. {
  40. memset(data, 0, sizeof(T) * pos);
  41. pos = 0;
  42. }
  43. void add(T t)
  44. {
  45. if(pos >= capacity)
  46. {
  47. int newCapacity = capacity * 2;
  48. T* t = new T[newCapacity];
  49. memcpy(t, data, capacity * sizeof(T));
  50. delete[] data;
  51. data = t;
  52. capacity = newCapacity;
  53. }
  54. data[pos] = t;
  55. pos++;
  56. }
  57. void remove(int index)
  58. {
  59. if(index < 0 || index >= pos)
  60. {
  61. return;
  62. }
  63. for(int i = index; i < pos - 1; i++)
  64. {
  65. data[i] = data[i + 1];
  66. }
  67. memset(data + pos - 1, 0, sizeof(T));
  68. pos--;
  69. }
  70. void forEach(void (*f) (T))
  71. {
  72. for(int i = 0; i < pos; i++)
  73. {
  74. f(data[i]);
  75. }
  76. }
  77. private:
  78. int capacity;
  79. int pos;
  80. T* data;
  81. };
  82. #endif