Vector.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Taken from: https://redstoner.com/forums/threads/840-minimal-class-to-replace-std-vector-in-c-for-arduino
  3. */
  4. #ifndef _VECTOR_H
  5. #define _VECTOR_H
  6. // Minimal class to replace std::vector
  7. template<typename Data>
  8. class Vector {
  9. size_t d_size; // Stores no. of actually stored objects
  10. size_t d_capacity; // Stores allocated capacity
  11. Data *d_data; // Stores data this is this "heap" we need a function that returns a pointer to this value, to print it
  12. public:
  13. Vector() : d_size(0), d_capacity(0), d_data(0) {}; // Default constructor
  14. Vector(Vector const &other) : d_size(other.d_size), d_capacity(other.d_capacity), d_data(0) //for when you set 1 vector = to another
  15. {
  16. d_data = (Data *)malloc(d_capacity*sizeof(Data));
  17. memcpy(d_data, other.d_data, d_size*sizeof(Data));
  18. }; // Copy constuctor
  19. ~Vector() //this gets called
  20. {
  21. free(d_data);
  22. }; // Destructor
  23. Vector &operator=(Vector const &other)
  24. {
  25. free(d_data);
  26. d_size = other.d_size;
  27. d_capacity = other.d_capacity;
  28. d_data = (Data *)malloc(d_capacity*sizeof(Data));
  29. memcpy(d_data, other.d_data, d_size*sizeof(Data));
  30. return *this;
  31. }; // Needed for memory management
  32. void push_back(Data const &x)
  33. {
  34. if (d_capacity == d_size) //when he pushes data onto the heap, he checks to see if the storage is full
  35. resize(); //if full - resize
  36. d_data[d_size++] = x;
  37. }; // Adds new value. If needed, allocates more space
  38. void Clear() //here
  39. {
  40. memset(d_data, 0, d_size);
  41. d_capacity = 0;
  42. d_size = 0;
  43. free(d_data);
  44. }
  45. size_t size() const { return d_size; }; // Size getter
  46. Data const &operator[](size_t idx) const { return d_data[idx]; }; // Const getter
  47. Data &operator[](size_t idx) { return d_data[idx]; }; // Changeable getter
  48. Data *pData() { return (Data*)d_data; }
  49. private:
  50. void resize()
  51. {
  52. d_capacity = d_capacity ? d_capacity * 2 : 1;
  53. Data *newdata = (Data *)malloc(d_capacity*sizeof(Data)); //allocates new memory
  54. memcpy(newdata, d_data, d_size * sizeof(Data)); //copies all the old memory over
  55. free(d_data); //free old
  56. d_data = newdata;
  57. };// Allocates double the old space
  58. };
  59. #endif