Array.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* Array.hpp :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2026/01/11 15:29:11 by bchanot #+# #+# */
  9. /* Updated: 2026/01/11 16:52:20 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #ifndef ARRAY_HPP
  13. # define ARRAY_HPP
  14. # include <iostream>
  15. # include <string>
  16. template <typename T>
  17. class Array
  18. {
  19. public:
  20. Array() { this->_elements = new T[]; };
  21. Array(unsigned int const n) : _size(n), _elements(new T[n]) {};
  22. Array( Array const & src ) : _size(src.size()), _elements(new T[this->_size]) {
  23. size_t fill = 0;
  24. while (fill < this->_size) {
  25. this->_elements[fill] = src[fill];
  26. fill++;
  27. }
  28. };
  29. ~Array() { delete[] this->_elements; };
  30. class IndexOutOfBounds : public std::exception {
  31. public:
  32. virtual const char *what() const throw() {
  33. return ("The index specified is out of bounds !");
  34. }
  35. };
  36. Array & operator=( Array const & rhs ) {
  37. if (rhs == *this)
  38. return *this;
  39. size_t fill = 0;
  40. this->_size = rhs.size();
  41. this->_elements = new T[this->_size];
  42. while (fill < this->_size) {
  43. this->_elements[fill] = rhs[fill];
  44. fill++;
  45. }
  46. return *this;
  47. };
  48. T &operator[](size_t idx) {
  49. if (idx >= this->_size)
  50. throw IndexOutOfBounds();
  51. return this->_elements[idx];
  52. };
  53. T const &operator[](size_t idx) const {
  54. if (idx >= this->_size)
  55. throw IndexOutOfBounds();
  56. return this->_elements[idx];
  57. };
  58. size_t size(void) const { return this->_size; };
  59. private:
  60. size_t _size;
  61. T *_elements;
  62. };
  63. #endif /* *********************************************************** ARRAY_H */