Created
October 27, 2024 05:47
-
-
Save dalkrawr/01cdda20d4032f52ceeec39ccea6e8a3 to your computer and use it in GitHub Desktop.
Stripped std::vector with a fixed capacity with the ability of being stack allocated.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <memory> | |
| #include <cassert> | |
| template<typename Type, size_t Capacity> | |
| class FixedVector | |
| { | |
| public: | |
| FixedVector() | |
| { | |
| m_Size = 0; | |
| for (size_t i = 0; i < Capacity; i++) | |
| new (&m_Data[i]) Type(); | |
| } | |
| FixedVector(const std::initializer_list<Type>& initList) | |
| { | |
| m_Size = 0; | |
| for (const auto& value : initList) | |
| pushBack(value); | |
| } | |
| void pushBack(const Type& elem) | |
| { | |
| assert(m_Size < Capacity && "Element count exceeds the capacity"); | |
| m_Data[m_Size] = elem; | |
| m_Size++; | |
| } | |
| template<class... Args> | |
| void emplaceBack(Args&&... args) | |
| { | |
| assert(m_Size < Capacity && "Element count exceeds the capacity"); | |
| new (&m_Data[m_Size]) Type(std::forward<Args>(args)...); | |
| m_Size++; | |
| } | |
| void popBack() | |
| { | |
| m_Size--; | |
| m_Data[m_Size] = {}; | |
| } | |
| size_t getSize() const | |
| { | |
| return m_Size; | |
| } | |
| Type* getData() | |
| { | |
| return m_Data; | |
| } | |
| const Type* getData() const | |
| { | |
| return m_Data; | |
| } | |
| Type& operator[](size_t pos) | |
| { | |
| assert(pos < m_Size); | |
| return m_Data[pos]; | |
| } | |
| const Type& operator[](size_t pos) const | |
| { | |
| assert(pos < m_Size); | |
| return m_Data[pos]; | |
| } | |
| Type* begin() | |
| { | |
| return m_Data; | |
| } | |
| Type* end() | |
| { | |
| return &m_Data[m_Size]; | |
| } | |
| const Type* begin() const | |
| { | |
| return m_Data; | |
| } | |
| const Type* end() const | |
| { | |
| return &m_Data[m_Size]; | |
| } | |
| private: | |
| Type m_Data[Capacity]; | |
| size_t m_Size; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment