UnsortedArrayList.h 1.8 KB

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