fork download
  1. #include <iostream>
  2.  
  3. struct MyArray
  4. {
  5. using value_type = double; // make value_type an alias for double.
  6.  
  7. explicit MyArray(unsigned size=64)
  8. : _storage(new value_type[size]), _capacity(size), _used(0) {}
  9.  
  10. ~MyArray() { delete [] _storage; }
  11.  
  12. unsigned capacity() const { return _capacity; }
  13. unsigned size() const { return _used; }
  14.  
  15. void add_value(value_type value);
  16.  
  17. friend std::ostream& operator <<(std::ostream& out, const MyArray& arr);
  18.  
  19. private:
  20.  
  21. value_type* _storage;
  22.  
  23. unsigned _capacity;
  24. unsigned _used;
  25. };
  26.  
  27. void MyArray::add_value(MyArray::value_type value)
  28. {
  29. if (size() == capacity())
  30. {
  31. // grow the array.
  32. throw; // until functionality is implemented.
  33. }
  34.  
  35. _storage[_used++] = value;
  36. }
  37.  
  38. // display a MyArray:
  39. std::ostream& operator <<(std::ostream& out, const MyArray& arr)
  40. {
  41. out << "{ ";
  42.  
  43. if (arr.size())
  44. {
  45. unsigned i = 0;
  46. while (i < arr.size() - 1)
  47. out << arr._storage[i++] << ", ";
  48. out << arr._storage[i] << ' ';
  49. }
  50.  
  51. return out << '}' ;
  52. }
  53.  
  54. int main()
  55. {
  56. MyArray arr(3);
  57. std::cout << arr << "\n\n";
  58.  
  59. arr.add_value(1.1);
  60. arr.add_value(2.2);
  61. arr.add_value(3.3);
  62.  
  63. std::cout << arr << '\n';
  64. }
  65.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
{ }

{ 1.1, 2.2, 3.3 }