Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <array>
- template<typename T, size_t S> // Makes it so it's not specific to integers
- class Array
- {
- public:
- constexpr size_t Size() const { return S; } // Function's sole job is to return constant value of whatever S is set to
- // Ref (&) prevents us from having copies and lets us assign into the index (ex: data[i] = 2;)
- // Size_t index used instead of int index because int allows for negative numbers and may not be the same size on all platforms
- T& operator[](size_t index) { return m_Data[index]; }
- 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
- // Way to access data within class
- T* Data() { return m_Data; }
- // Const version
- const T* Data() const { return m_Data; }
- private:
- T m_Data[S]; // Replaced int m_Data[S];
- };
- int main()
- {
- int size = 5;
- Array<int, 5> data; // Version of this class where T is set to int and size set to 5
- // memset(data.Data(), 0, data.Size() * sizeof(int)); // Set all integers inside of our array to 0 by setting all memory to 0.
- // 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
- memset(&data[0], 0, data.Size() * sizeof(int));
- data[1] = 5;
- data[4] = 8;
- for (size_t i = 0; i < data.Size(); i++) // Indexes throughout data
- {
- std::cout << data[i] << std::endl;
- }
- std::cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement