Fixed allocation std::vector
You can implement or reuse boost's static_vector; A variable-size array container with fixed capacity.
You can always use a C-style array (same as underlying in std::array
) as vectors aren't supposed to be static
int arr[5]; // static array of 5 integers
To have it more useful you can wrap it in a class template to hide the C-style Example:
template<class type, std::size_t capacaty>
class StaticVector {
private:
type arr[capacaty];
std::size_t m_size;
public:
StaticVector() : m_size(0) {}
type at(std::size_t index) {
if (index >=0 && index < m_size) {
return arr[index];
}
return type();
}
void remove(std::size_t index) {
if (index >=0 && index < m_size) {
for (std::size_t i=index; i < m_size-1; i++) {
arr[i] = arr[i+1];
}
m_size--;
}
}
void push_back(type val) {
if (m_size < capacaty) {
arr[m_size] = val;
m_size++;
}
}
std::size_t size() {
return m_size;
}
};
Example with it in use: https://onlinegdb.com/BkBgSTlZH