Facebook
From Eratic Octupus, 3 Months ago, written in C++.
Embed
Download Paste or View Raw
Hits: 58
  1. #include <iostream>
  2.  
  3. template<typename T>
  4. class Array
  5. {
  6. private:
  7.         int m_capacity = 0;
  8.         T* m_data = nullptr;
  9. public:
  10.         Array(int capacity) : m_capacity(capacity), m_data(new T[capacity]{})
  11.         {
  12.         }
  13.  
  14.         ~Array()
  15.         {
  16.                 delete[] m_data;
  17.         }
  18.  
  19.         T& operator[](int index)
  20.         {
  21.                 return m_data[index];
  22.         }
  23.  
  24.         friend std::ostream& operator<< (std::ostream& stream, const Array& array)
  25.         {
  26.                 for (int i = 0; i <= array.m_capacity - 1; i++)
  27.                 {
  28.                         // how can i check in here if value under this key contains something that user set manually?
  29.                         stream << i << ": " << array.m_data[i] << std::endl;
  30.                 }
  31.                 return stream;
  32.         }
  33. };
  34.  
  35.  
  36.  
  37. int main()
  38. {
  39.         Array<int> test = Array<int>(5);
  40.         test[0] = 1;
  41.         test[1] = 0; // this 0 should be also displayed
  42.         test[2] = 3;
  43.  
  44.         /*
  45.         result right now:
  46.         0: 1
  47.         1: 0
  48.         2: 3
  49.         3: 0
  50.         4: 0
  51.  
  52.         what i would like to achieve:
  53.         0: 1
  54.         1: 0
  55.         2: 3
  56.  
  57.         so as you can see i would like to not display element 3,4 because i haven't set these values.
  58.         */
  59.         std::cout << test << std::endl;
  60.         std::getchar();
  61.         return 0;
  62. }