ArrayList.h 1.9 KB

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