Advertisement
Ginsutime

Array Cherno 3 - Size_t

Feb 20th, 2022
1,105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <array>
  3.  
  4. template<typename T, size_t S> // Makes it so it's not specific to integers
  5. class Array
  6. {
  7. public:
  8.     constexpr size_t Size() const { return S; } // Function's sole job is to return constant value of whatever S is set to
  9.  
  10.     // Ref (&) prevents us from having copies and lets us assign into the index (ex: data[i] = 2;)
  11.     // Size_t index used instead of int index because int allows for negative numbers and may not be the same size on all platforms
  12.     T& operator[](size_t index) { return m_Data[index]; }
  13.     const T& operator[](size_t index) const { return m_Data[index]; } // With this, can still call the function if the instance of array is constant
  14.  
  15.     // Way to access data within class
  16.     T* Data() { return m_Data; }
  17.     // Const version
  18.     const T* Data() const { return m_Data; }
  19. private:
  20.     T m_Data[S]; // Replaced int m_Data[S];
  21. };
  22.  
  23. int main()
  24. {
  25.     int size = 5;
  26.     Array<int, 5> data; // Version of this class where T is set to int and size set to 5
  27.  
  28.     // memset(data.Data(), 0, data.Size() * sizeof(int)); // Set all integers inside of our array to 0 by setting all memory to 0.
  29.     // Not necessary, can do this the other way by taking first index of array and grab its index since the stack is contiguous in memory
  30.     memset(&data[0], 0, data.Size() * sizeof(int));
  31.  
  32.     data[1] = 5;
  33.     data[4] = 8;
  34.  
  35.     for (size_t i = 0; i < data.Size(); i++) // Indexes throughout data
  36.     {
  37.         std::cout << data[i] << std::endl;
  38.     }
  39.  
  40.     std::cin.get();
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement