ArrayList.h 1.7 KB

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