Vector.h 2.2 KB

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